hashlib模块 configparser模块 logging模块

一,    importer      hashlib

         将任意长度字符串转换成定长的密文的字符串,字符串里的每个字符都是一个十六进制的数字,这个密文是不可逆的

         算法:  特点:  在任何语言环境下,对于同一个字符串,用相同的算法,相同的手段去进行摘要,获得的值总是相同的

                              只要是不相同的字符串,得到得结果一定不同

                   种类:  包含    md5 算法     sha1  算法

                           md5 是一个算法,32位的字符串,每个字符都是一个十六进制,  效率快 算法相对简单,用的时间较久,市面上已经形成了撞库,

import hashlib
ret = hashlib.md5(b'kajsbfkq')     # 算出字符串的密文
print(ret.hexdigest())
# 动态加盐
username = input('username : ')
passwd = input('password : ')
md5obj = hashlib.md5(username.encode('utf-8'))      #得到一个对象
md5obj.update(passwd.encode('utf-8'))               #通过限制账号的不重叠,然后作为盐加到密码中
print(md5obj.hexdigest())
View Code

                         sha1  也是一个算法,40位的字符串,每个字符都是一个十六进制, 算法相对复杂 计算速度也慢

 文件的一致性校验

# 小文件的一致性校验
md5_obj = hashlib.md5()
with open('xx文件','rb') as f:
    md5_obj.update(f.read())
    ret1 = md5_obj.hexdigest()

md5_obj = hashlib.md5()
with open('yy文件','rb') as f1:
    md5_obj.update(f1.read())
    ret2 = md5_obj.hexdigest()
print(ret1,ret2)
View Code

大文件一致性校验:

还没写,待插入

二,import    configparser

#这是一个好多软件常见的配置文件
[DEFAULT]
ServerAliveInterval = 45
Compression = yes
CompressionLevel = 9
ForwardX11 = yes
[bitbucket.org]
User = hg
[topsecret.server.com]
Port = 50022
ForwardX11 = no
#用python生成器生成这样的文档
import configparser
config = configparser.ConfigParser()
config["DEFAULT"] = {'ServerAliveInterval': '45',
                      'Compression': 'yes',
                     'CompressionLevel': '9',
                     'ForwardX11':'yes'
                     }
config['bitbucket.org'] = {'User':'hg'}
config['topsecret.server.com'] = {'Host Port':'50022','ForwardX11':'no'}
with open('example.ini', 'w') as configfile:
   config.write(configfile)
#查找文件,理解成大字典,基于字典的形式
import configparser
config = configparser.ConfigParser()
print(config.sections())        #  []
config.read('example.ini')
print(config.sections())        #   ['bitbucket.org', 'topsecret.server.com']
print('bytebong.com' in config) # False
print('bitbucket.org' in config) # True
print(config['bitbucket.org']["user"])  # hg
print(config['DEFAULT']['Compression']) #yes
print(config['topsecret.server.com']['ForwardX11'])  #no
print(config['bitbucket.org'])          #<Section: bitbucket.org>
for key in config['bitbucket.org']:     # 注意,有default会默认default的键
    print(key)
print(config.options('bitbucket.org'))  # 同for循环,找到'bitbucket.org'下所有键
print(config.items('bitbucket.org'))    #找到'bitbucket.org'下所有键值对
print(config.get('bitbucket.org','compression')) # yes       get方法Section下的key对应的value
#增删改操作
import configparser
config = configparser.ConfigParser()
config.read('example.ini')
config.add_section('yuan')
config.remove_section('bitbucket.org')
config.remove_option('topsecret.server.com',"forwardx11")
config.set('topsecret.server.com','k1','11111')
config.set('yuan','k2','22222')
config.write(open('new2.ini', "w"))

三,logging  模块    

       日志的分级:

     logging.basicConfig(level=logging.DEBUG)   括号里的level是配置的等级模式,这里的等级最低是INFO,除非程序出错需要调试的时候才用DEBUG

      logging.debug('debug  message')      ===>  调试模式

      logging.info('info  message')               ===>  基础信息

      logging.warning('warning message')   ===> 警告

     logging.error('error  message')             ===>错误

      logging.cirtical('cirtical  message')       ===>严重错误

    (1)普通配置型的   简单的  可定制化差

       定制普通函数自定义日志如下

logging.basicConfig(level=logging.DEBUG,
                    format='%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s',
                    datefmt='%a, %d %b %Y %H:%M:%S',
                    filename='test.log')#括号里面的参数可以自由配置
logging.debug('调试模式')
logging.info('用户信息')
logging.warning('警告信息')
logging.error('错误信息')
logging.critical('严重错误')
View Code

     那么常用的配置参数有哪些,如下

logging.basicConfig()函数中可通过具体参数来更改logging模块默认行为,可用参数有:

filename:用指定的文件名创建FiledHandler,这样日志会被存储在指定的文件中。
filemode:文件打开方式,在指定了filename时使用这个参数,默认值为“a”还可指定为“w”。
format:指定handler使用的日志显示格式。
datefmt:指定日期时间格式。
level:设置rootlogger(后边会讲解具体概念)的日志级别
stream:用指定的stream创建StreamHandler。可以指定输出到sys.stderr,sys.stdout或者文件(f=open(‘test.log’,’w’)),默认为sys.stderr。若同时列出了filename和stream两个参数,则stream参数会被忽略。

format参数中可能用到的格式化串:
%(name)s Logger的名字
%(levelno)s 数字形式的日志级别
%(levelname)s 文本形式的日志级别
%(pathname)s 调用日志输出函数的模块的完整路径名,可能没有
%(filename)s 调用日志输出函数的模块的文件名
%(module)s 调用日志输出函数的模块名
%(funcName)s 调用日志输出函数的函数名
%(lineno)d 调用日志输出函数的语句所在的代码行
%(created)f 当前时间,用UNIX标准的表示时间的浮 点数表示
%(relativeCreated)d 输出日志信息时的,自Logger创建以 来的毫秒数
%(asctime)s 字符串形式的当前时间。默认格式是 “2003-07-08 16:49:45,896”。逗号后面的是毫秒
%(thread)d 线程ID。可能没有
%(threadName)s 线程名。可能没有
%(process)d 进程ID。可能没有
%(message)s用户输出的消息
View Code

     (2)对象配置型  复杂的  可定制化强

import logging
#第一步,创建
logger = logging.getLogger()              #实例化logger对象  注意这个对象是在程序中用来调用各种日志命令来记录的
fh = logging.FileHandler('logger_log',encoding='utf-8')   #创建一个文件管理操作符
sh = logging.StreamHandler()                                #创建一个屏幕管理操作符
format1 = logging.Formatter('%(asctime)s-%(name)s-%(levelname)s-%(message)s') #创建日志输出格式(这个格式可自定义)
#第二步,绑定屏幕和文件日志格式
fh.setFormatter(format1)  #文件绑定日志格式
sh.setFormatter(format1)  #屏幕绑定日志格式
#第三部,对象绑定文件操作符,对象绑定屏幕操作符,  注意:可以绑定多个文件,可拓展行高
logger.addHandler(fh)      #对象绑定文件操作符
logger.addHandler(sh)      #对象绑定屏幕操作符
#到这步对象已经完成装备就绪,可以调用日志的方法来记录日志
logger.debug('debug message')      # 调试模式
logger.info('我的信息')        # 基础信息
logger.warning('warning message')  # 警告
logger.error('error message')      # 错误
logger.critical('critical message')# 严重错误
#注意这些方法可以出现在程序中需要记录的时候就调用就行
View Code

          

     

   

         

         

原文地址:https://www.cnblogs.com/laogao123/p/9451680.html