Common module 3 hashlib, configparser, logging

One, two common module

hashlib module

hashlib provides a summary of common algorithms, such as md5 and sha1 and so on.

So what is it digest algorithm? Digest algorithm, also known as hash algorithm, hash algorithm. It is through a function to convert data for any length of a fixed length data string (typically represented by a string of 16 hexadecimal).

Note: The summary is not an algorithm decryption algorithm. (Digest algorithm to detect a string of whether the change occurs)

It should be painted: 1 file checksums do

   2. Password

      Passwords can not be decrypted, but the method can hit the library, with the 'salt' of the problem can be solved hit library. All a bit more complex to set a password to be set later time.

. 1 Import hashlib 2 # md5_obj = hashlib.md5 () unsalted . 3 md5_obj hashlib.md5 = ( 'Nezha'. Encode ( 'UTF-. 8')) # with salt (let the stronger your password) 4 md5_obj.update ( '123456'. encode ( 'UTF-. 8')) . 5 Print (md5_obj.hexdigest ()) . 6 md5_obj.update ( 'Hello'. encode ( 'UTF-. 8')) . 7 Print (md5_obj.hexdigest ()) . 8 # ----------- . 9 User = 'Haiyan' 10 password = '123456' . 11 md5_obj = hashlib.md5 ( User . encode ( 'UTF-. 8')) # Salt (even if the person's password and your password is the same,12 # that you add salt only after your user name corresponds to your password) 13 md5_obj.update (password. Encode ( 'UTF-8')) 14 Print (md5_obj.hexdigest ()) 15 16 user password
User Password View Code
1 import hashlib 2 md5_obj = hashlib.md5() 3 import os 4 filesize = os.path.getsize('filename') #文件大小 5 f = open('filename','rb') 6 while filesize>0: 7 if filesize > 1024: 8 content = f.read(1024) 9 filesize -= 1024 10 else: 11 content = f.read(filesize) 12 filesize -= filesize 13 md5_obj.update(content) 14Line for F in #: 15 # md5_obj.update (. Line encode ( 'UTF-. 8')) 16 md5_obj.hexdigest () . 17 18 is file checksum (document detecting no change)
File checksum View Code

configparser module

This is similar to the profile module is adapted to windows ini file format, may comprise one or more sections (sectionTop), each node can have a plurality of parameters (key = value).

1. Create a file

1 import configparser 2 config = configparser.ConfigParser() 3 config["DEFAULT"] = {'ServerAliveInterval': '45', 4 'Compression': 'yes', 5 'CompressionLevel': '9', 6 'ForwardX11':'yes' 7 } 8 config['bitbuck et.org'] = {'User':'hg'} 9 config['topsecret.server.com'] = {'Host Port':'50022','ForwardX11':'no'} 10 with open('example.ini', 'w') as configfile: 11 config.create a file1312(configfile)the Write
Create a file View Code

2. Find Files

. 1 Import ConfigParser 2 config = configparser.ConfigParser () . 3 # Print (config.sections ()) . 4 config. Read ( 'example.ini') . 5 Print (config.sections ()) # file is read out inside the group , 6 # and inside [the DEFAULT] group is not displayed . 7 Print ( 'bytebong.com' in config) # False . 8 Print ( 'bitbucket.org' in config) # True . 9 Print (config [ 'bitbucket.org'] [ " User "]) # Hg 10 Print (config [ 'the DEFAULT'] [ 'Compression']) #yes . 11 Print(config [ 'topsecret.server.com'] [ 'the ForwardX11']) #no 12 is Print (config [ 'bitbucket.org']) # <Section: bitbucket.org> 13 is for Key in config [ 'bitbucket.org' ]: # Note that there are default default default key 14 Print (key) 15 Print (config.options ( 'bitbucket.org')) # loop with for, find 'bitbucket.org' all key 16 Print (config. items ( 'bitbucket.org')) # found under 'bitbucket.org' all key-value pairs . 17 Print (config.get ( 'bitbucket.org', 'compression')) in the Key # yes get value method corresponding to Section 18 19 Finding files
Find File View Code

3. CRUD operations

1 import configparser 2 config = configparser.ConfigParser() 3 config.read('example.ini') 4 config.add_section('yuan') 5 # config.remove_section('bitbucket.org') #删除组 6 # config.remove_option('topsecret.server.com',"forwardx11") #删除组里面的项 7 config.set('topsecret.server.com','k1','11111') 8 config.set('yuan','k2','22222') 9 config.write(open('new2.ini', "w")) 10 11
增删改操作 View Code

logging模块

函数式简单配置

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

1 只显示大于等于warning基本的日志,这说明默认的日志级别设置为warning 2 (日志级别等级critical>error>warning>info>debug) 3 import logging 4 logging.debug('debug message') 5 logging.info('info message') 6 logging.warning('warning message') #warning 警告(从警告开始才执行) 7 logging.error('error message') #error 错误 8 logging.critical('critical message') #比错误更严重的级别
View Code

配置参数

1 logging.basicConfig()函数中可通过具体参数来更改logging模块默认行为,可用参数有: 2 3 filename:用指定的文件名创建FiledHandler,这样日志会被存储在指定的文件中。 4 filemode:文件打开方式,在指定了filename时使用这个参数,默认值为“a”还可指定为“w”。 5 format:指定handler使用的日志显示格式。 6 datefmt:指定日期时间格式。 7 level:设置rootlogger(后边会讲解具体概念)的日志级别 8 stream:用指定的stream创建StreamHandler。可以指定输出到sys.stderr,sys.stdout或者文件(f=open(‘test.log’,’w’)),默认为sys.stderr。若同时列出了filename和stream两个参数,则stream参数会被忽略。 9 10 format参数中可能用到的格式化串: 11 %(name)s Logger的名字 12 %(levelno)s 数字形式的日志级别 13 %(levelname)s 文本形式的日志级别 14 %(pathname)s 调用日志输出函数的模块的完整路径名,可能没有 15 %(filename)s 调用日志输出函数的模块的文件名 16 %(module)s 调用日志输出函数的模块名 17 %(funcName)s 调用日志输出函数的函数名 18 %(lineno)d 调用日志输出函数的语句所在的代码行 19 %(created)f 当前时间,用UNIX标准的表示时间的浮 点数表示 20 %(relativeCreated)d 输出日志信息时的,自Logger创建以 来的毫秒数 21 %(asctime)s 字符串形式的当前时间。默认格式是 “2003-07-08 16:49:45,896”。逗号后面的是毫秒 22 %(thread)d 线程ID。可能没有 23 %(threadName)s 线程名。可能没有 24 %(process)d 进程ID。可能没有 25 %(message)s用户输出的消息 26 27 配置参数
View Code

有两种方式去应用logging模块

1.设置config

1 import logging 2 logging.basicConfig( 3 level=logging.DEBUG , #多输出一些细节 4 # level = logging.WARNING #就不用输出那些细节了 5 format = '%(name)s %(asctime)s [%(lineno)d] ---%(message)s', #本身就存在在python语法中,拿过来用就行了 6 # level和format也是不能变的,它是参数,不是变量 7 # %(lineno)d指定代码块的行 8 # %(name)s当前管理员的用户 9 datefmt = '%d/%m/%Y %H:%M:%S',#指定日期时间格式 10 filename = 'logging_info' #自动创建了一个文件,并且把日志写到了文件里 11 12 ) 13 logging.debug('debug message') 14 logging.info('info message') 15 logging.warning('warning message') 16 logging.error('error message') 17 logging.critical('critical message') 18 19 设置config
View Code

2.logger对象配置

可以控制输入到文件,也可以输入到屏幕

可以同时在几个文件中输出

1 import logging 2 def mylogger(filename,file=True,stream=True): 3 logger = logging.getLogger() 4 formater = logging.Formatter( 5 fmt='%(name)s %(asctime)s [%(lineno)d] ---%(message)s', 6 datefmt='%d/%m/%Y %H:%M:%S' # 时间格式 7 ) 8 logger.setLevel(logging.DEBUG) #指定日志打印的等级 9 if file: 10 file_handler = logging.FileHandler('logging.log',encoding='utf-8')# 创建一个handler,用于写入日志文件 11 file_handler.setFormatter(formater) # 文件流,文件操作符 12 logger.addHandler(file_handler) 13 if stream: 14 stream_handler = logging.StreamHandler() # 再创建一个handler,用于输出到控制台 15 stream_handler.setFormatter(formater) #屏幕流,屏幕操作流 16 #如果想让文件流和屏幕流输出的东西的格式不一样,那么就在写一个 格式formater1,这样就可以了 17 logger.addHandler(stream_handler) 18 return logger 19 logger = mylogger('logging.log',file=False) 20 logger.warning('啦啦啦啦') 21 logger.debug('debug message') 22 23 logger对象
View Code

logging库提供了多个组件:Logger、Handler、Filter、Formatter。Logger对象提供应用程序可直接使用的接口,Handler发送日志到适当的目的地,Filter提供了过滤日志信息的方法,Formatter指定日志显示格式。另外,可以通过:logger.setLevel(logging.Debug)设置级别,当然,也可以通过

fh.setLevel(logging.Debug)单对文件流设置某个级别。

 

 

归类 :  Python相关

Guess you like

Origin www.cnblogs.com/lz1996/p/11567619.html