python common module (3)

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.

hashlib Import 
 2 = # md5_obj hashlib.md5 () unsalted 
 3 md5_obj = hashlib.md5 ( 'nezha'.encode ( ' utf-8 ')) # with salt (let your password firmer a) 
 . 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 being password and your password is the same, 
12 # then 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 ())

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)
14 # for line in f:
15 #     md5_obj.update(line.encode('utf-8'))
16 md5_obj.hexdigest()

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

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.write(configfile)

2.查找文件
ConfigParser Import 
 2 configparser.ConfigParser config = () 
 . 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,There are default default default key 
14 Print (Key) 
15 Print (config.options ( 'bitbucket.org')) # with a for loop, find 'bitbucket.org' in all key
16 print (config.items ( 'bitbucket.org' )) # found 'bitbucket.org' all key-value pairs
17 print (config.get ( 'bitbucket.org', 'compression')) # key in the method of Section yes get the corresponding value

 3. CRUD operations

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"))

logging module

 Functional simple configuration

Python's logging module logs printed by default to the standard output, and only shows a greater than or equal WARNING level log, indicating that the default log level WARNING (log level Level CRITICAL> ERROR> WARNING> INFO> DEBUG), the default log format for the log level: Logger name: user output messages.

Copy the code
A warning display is greater than substantially equal to the log, indicating that the default warning level is set to log 
2 (log level Level Critical> error> warning> info> Debug) 
. 3 Import the logging 
. 4 logging.debug ( 'Debug Message') 
. 5 the logging. info ( 'Message info') 
. 6 logging.warning ( 'warning Message') #warning warning (warning only performed from the start) 
. 7 logging.error ( 'error Message') #error errors 
8 logging.critical ( 'critical message') # more serious than the error level
Copy the code

 Configuration parameters

logging.basicConfig () function can be changed by logging module specific parameters default behavior, the available parameters are: 
 2 
 3 filename: Creating FiledHandler with the specified file name, such logs are stored in the file specified. 
 4 filemode: Open file using the filename parameter is specified, the default value "a" may also be designated as "w". 
 5 format: log handler specified display format. 
 6 datefmt: specify the date and time format. 
 7 level: Set rootlogger (behind will explain specific concepts) log level 
 8 stream: StreamHandler created with the specified stream. Can specify the output to sys.stderr, sys.stdout or file (f = open ( 'test.log' , 'w')), default sys.stderr. If both lists the filename and stream two parameters, the stream parameter is ignored. 
 . 9 
10 may be used in the format parameter string format: 
. 11% (name) is the name of S Logger 
log level 12% (levelno) s digital form 
13% (levelname) s text log level 
14% (pathname) s the full path name of the module to call log output function, may not be 
15% (filename) s calling module log output function of the file name 
16% (module) s call log output function module name 
17% (funcName) s call log output name of the function
Line 18% (lineno) d log output function call statement where
19% (created) f the current time, represented by a standard floating point representation UNIX time 
, since the number of milliseconds to create Logger at 20% (relativeCreated) d log information output 
21% (asctime) s current time string . The default format is "2003-07-0816: 49: 45,896." Milliseconds after the comma is 
22% (thread) d thread ID. It may not be 
23% (threadName) s thread name. It may not be 
24% (process) d process ID. May not be 
25% (message) s user output message

 

There are two ways to apply logging module

1. Set config

the logging Import 
 2 logging.basicConfig ( 
 . 3 Level = logging.DEBUG, some details of the multiple output # 
 4 # level = logging.WARNING # those details would not output a 
 5 format = '% (name) s% (asctime) s [% ( lineno) d] ---% (message ) s', # itself syntax present in the python, take over the line using 
 6 # level format and also can not change, it is a parameter, not the variable 
 7 #% (lineno) d specify the code block row 
 8 #% (name) s current administrator user 
 9 datefmt = '% d /% m /% Y% H:% m:% S', # specified date time format 
10 filename = 'logging_info '# automatically creates a file, and the writing to a file 
. 11 
12 is) 
13 is logging.debug (' Debug Message ') 
14 logging.info (' Message info ') 
15 logging.warning (' warning Message ') 
16 the logging .error ( 'error Message') 
. 17 logging.critical ( 'Critical Message')

2.logger object configuration

Can control the input to the file, you can also enter to the screen

It can be output simultaneously in several files

the logging Import 
 2 DEF MyLogger (filename, File = True, Stream = True): 
 . 3 Logger logging.getLogger = () 
 . 4 logging.Formatter the Formater = ( 
 . 5 FMT = '% (name) S% (the asctime) S [% (lineno ) D] ---% (Message) S ', 
 . 6 datefmt =' D% /% m /% the Y% H:% m:% S '# time format 
 . 7) 
 . 8 Logger.setLevel (logging.DEBUG) # specify level print log 
 . 9 IF file: 
10 file_handler are logging.FileHandler = ( 'logging.log', encoding = 'UTF-. 8') # Create a handler, for writing the log file 
11 file_handler.setFormatter (formater) # file stream , file operator 
12 is logger.addHandler (file_handler are) 
13 is IF stream:  
14 stream_handler logging.StreamHandler = () # then create a Handler, for output to the console
15 stream_handler.setFormatter (the Formater) # screen flow, the flow operation screen 
format # 16 if you want the output file stream and screen flow is not the same thing, then write in a format formater1, so it 
17 logger.addHandler (stream_handler ) 
18 is return Logger 
. 19 Logger = MyLogger ( 'logging.log', File = False) 
20 is logger.warning ( 'la la') 
21 is logger.debug ( 'Debug Message')

logging library provides a number of components: Logger, Handler, Filter, Formatter. Logger object provides an interface application can be used directly, Handler send logs to the appropriate destination, Filter provides a method of filtering log information, Formatter display format specified log. Further, by: logger.setLevel (logging.Debug) set the level, of course, can also

fh.setLevel (logging.Debug) set a single-file stream level.

Guess you like

Origin www.cnblogs.com/intruder/p/10928803.html