4-23 模块 hashlib ,configparser,loging,collections

1,hashlib模块的补充(摘要算法)

          1,Sha1的用法和md5的类似,通常用一个40位的16进制字符串表示。比SHA1更安全的算法是SHA256和SHA512,不过越安全的算法越慢,而且摘要长度更长。

           2,一段字符串直接进行摘要和分成几段摘要的结果是一致的。

import hashlib
md5obj = hashlib.md5()
# md5obj.update(b'hello,alex,I know your password is alex3714')
md5obj.update(b'hello,')
md5obj.update(b'alex,')
md5obj.update(b'I know your ')
md5obj.update(b'password is alex3714')
print(md5obj.hexdigest())
#882744b4dca21988e5716a235584a67b
# 882744b4dca21988e5716a235584a67b

           3,可以用hashlib模块,对两个文件进行一致性的校验。

def check(filename):
    md5obj = hashlib.md5()
    with open(filename,'rb')as f:
        content = f.read(1024)
        md5obj.update(content)
    return md5obj.hexdigest()

ret1 = check('file1')
ret2 = check('file2')
print(ret1)
print(ret2)
View Code

        对两个文件进行一致性校验?

import hashlib
def compare(filename1,filename2):
    md5sum = []
    for file in [filename1,filename2]:
        md5 = hashlib.md5()
        with open(file,'rb')as f:
            while True:
                content = f.read(1024)
                if content:
                    md5.update(content)
                else:
                    break
            md5sum.append(md5.hexdigest())
    if md5sum[0] == md5sum[1]:return True
    else:return False
print(compare('f1','f2'))
View Code

2,cofigparser模块(配置文件模块)

该模块适用于配置文件的格式与windows ini文件类似,可以包含一个或多个节(section),每个节可以有多个参数(键=值)。

           1,在配置文件中,必须分组。

            2,组名可以随便起,也可以叫DEFAULT,有特殊意义。

            3,section(小节)可以直接操作它的对象来获取所有的节的消息。

            4,option可以通过找到的节来看多有的项。

import configparser
config = configparser.ConfigParser()
config.read('example.ini')
print(config.sections())        #  查看所有的节 但是默认不显示DEFAULT []
print('bitbucket.org' in config) # True  验证某个节是否在文件中
print('bytebong.com' in config) # False
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
View Code

3,logging模块(日志)

  logging日志 模块 :给我们在内部操作的时候提供很多遍历,给用户提供更多的信息,在程序使用的过程中自己调试需要看的信息,帮助程序员排查程序的问题。

  logging模块它不能自己打印内容 ,只能根据程序员写的代码来完成功能。

  logging模块提供5个日志级别,从低到高依次:debug  info  warning  error  critical   。默认从warning模式开始显示。

  logging日志分为两中模式:

    1,函数式简单配置,默认情况下Python的logging模块将日志打印到了标准输出中,且只显示了大于等于WARNING级别的日志,这说明默认的日志级别设置为WARNING(日志级别等级CRITICAL > ERROR > WARNING > INFO > DEBUG),默认的日志格式为日志级别:Logger名称:用户输出消息。

              问题:编码问题,不能同时输出到文件和屏幕。

import logging
# 默认情况下 只显示 警告 及警告级别以上信息
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 = 'userinfo.log'
                    )
logging.debug('debug message')       # debug 调试模式 级别最低
logging.info('info message')         # info  显示正常信息
logging.warning('warning message')   # warning 显示警告信息
logging.error('error message')       # error 显示错误信息
logging.critical('critical message') # critical 显示严重错误信息

4,logger对象配置

  高可定制化,首先创造一个logger对象,再创造文件句柄,屏幕句柄,再创造格式formatter,使用文件句柄和屏幕句柄绑定格式,logger对象和句柄关联。

import logging
logger = logging.getLogger()  # 实例化了一个logger对象

fh = logging.FileHandler('test.log',encoding='utf-8')    # 实例化了一个文件句柄
sh = logging.StreamHandler()

fmt = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
fh.setFormatter(fmt)   # 格式和文件句柄或者屏幕句柄关联
sh.setFormatter(fmt)
sh.setLevel(logging.WARNING)

 吸星大法
logger.addHandler(fh)  # 和logger关联的只有句柄
logger.addHandler(sh)
logger.setLevel(logging.DEBUG)

logger.debug('debug message')       # debug 调试模式 级别最低
logger.info('info message')         # info  显示正常信息
logger.warning('warning message')   # warning 显示警告信息
logger.error('error message')       # error 显示错误信息
logger.critical('critical message')
View Code
 

猜你喜欢

转载自www.cnblogs.com/yzxing/p/8921336.html
今日推荐