1,hashlib Module---digest algorithm
Import= hashlib.md5 () md5.update ('How to use themd5 in Python hashlib? ' Print md5.hexdigest () calculates the result as follows: d26a53750bc40b38b65a520292f69306
Encrypt with MD5
If you have a large amount of data, you can call Update () multiple times in chunks, and the result is the same:
MD5 = hashlib.md5 () md5.update(') md5.update ('python Hashlib? ' )print md5.hexdigest ()
MD5 is the most common digest algorithm and is fast enough to generate a fixed byte of bytes, typically represented by a 32-bit 16 binary string. Another common digest algorithm is SHA1, which calls SHA1 and calls MD5 exactly like:
Import= hashlib.sha1 () sha1.update (") sha1.update ( ' python hashlib? ' )print sha1.hexdigest ()
The result of the SHA1 is a bit byte, which is usually represented by a 40-bit 16 binary string. Algorithms that are more secure than SHA1 are SHA256 and SHA512, but the more secure the algorithm is, the slower it is, and the longer the digest length.
2,configparser Module
The module applies to configuration files in a format similar to a Windows INI file, and can contain one or more sections (section), each of which can have multiple parameters (key = value).
Create a file
Here's a look at a lot of common document formats for software:
= * = 9 = yes = HG = 50022 = no
What if you want to use Python to generate a document like this?
ImportConfigparserconfig=Configparser. Configparser () config["DEFAULT"] = {'Serveraliveinterval':' $', '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)
Find Files
ImportConfigparserconfig=Configparser. Configparser ()#---------------------------Find the contents of a file in a dictionary-based formatPrint(Config.sections ())# []Config.read ('Example.ini')Print(Config.sections ())#[' bitbucket.org ', ' topsecret.server.com ']Print('bytebong.com' inchConfig#FalsePrint('bitbucket.org' inchConfig#TruePrint(config['bitbucket.org']["User"])#HGPrint(config['DEFAULT']['Compression'])#YesPrint(config['topsecret.server.com']['ForwardX11'])#NoPrint(config['bitbucket.org'])#<Section:bitbucket.org> forKeyinchconfig['bitbucket.org']:#Note that a key with default defaults will Print(Key)Print(Config.options ('bitbucket.org'))#same for loop, find all keys under ' bitbucket.org 'Print(Config.items ('bitbucket.org'))#Find all key-value pairs under ' bitbucket.org 'Print(Config.get ('bitbucket.org','Compression'))#Yes Get method section key corresponding to value
Adding and removing changes operation
ImportConfigparserconfig=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 module function Simple configuration
import logging Logging.debug ( " debug message ) logging.info ( " info message " ) Logging.warning ( " warning message " ) logging.error ( " Error message " ) logging.critical ( " critical message ")
By default, Python's logging module prints the logs to standard output and only displays logs that are greater than or equal to the warning level, indicating that the default logging level is set to warning (log level level critical > ERROR > WARNING > INFO > DEBUG), the default log format is log level: Logger name: User output message.
Flexible configuration log level, log format, output location:
ImportLogging 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='/tmp/test.log', FileMode='W') Logging.debug ('Debug Message') Logging.info ('Info Message') logging.warning ('warning Message') Logging.error ('error Message') logging.critical ('Critical Message')
Configuration parameters:
The logging.basicconfig () function can change the default behavior of the logging module through specific parameters, with the available parameters: FileName: Creates a filedhandler with the specified file name so that the log is stored in the specified files. FileMode: File is opened by using this parameter when filename is specified, and the default value is "a" and can be specified as "W". Format: Specifies the log display format used by handler. DATEFMT: Specifies the date time format. Level: Set Rootlogger (The following explains the specific concept) stream: Create Streamhandler with the specified stream. You can specify output to Sys.stderr,sys.stdout or file (f=open (' Test.log ', ' W ')), default is Sys.stderr. If you list both the filename and stream two parameters, the stream parameter is ignored. formatting strings that may be used in the format parameter:%(name) s Logger's name%(Levelno) s log level in digital form%(levelname) s log level in text form%(pathname) s The full pathname of the module that invokes the log output function, possibly without%(filename) s The file name of the module that invokes the log output function%module Name of the log output function called by (module) s%(funcName) s function name of the call log output function%(Lineno) d The line of code where the statement that invokes the log output function%(created) F current time, represented by the UNIX standard floating-point number representing the time%(relativecreated) d when the log information is output, the number of milliseconds since logger was created% (asctime) s The current time in string form. The default format is "2003-07-08 16:49:45,896". The comma is followed by milliseconds%(thread) d thread ID. Probably not .%(threadname) s thread name. Probably not .%(process) d ID. Probably not .% (message) s user-output message
View CodeLogger Object Configuration
ImportLogginglogger=Logging.getlogger ()#create a handler to write to the log fileFH = logging. Filehandler ('Test.log', encoding='Utf-8') #create another handler for output to the consoleCH =logging. Streamhandler () Formatter= Logging. Formatter ('% (asctime) s-% (name) s-% (levelname) s-% (message) s') Fh.setlevel (logging. DEBUG) Fh.setformatter (formatter) ch.setformatter (formatter) logger.addhandler (FH)#Logger object can add multiple FH and CH objectslogger.addhandler (CH) logger.debug ('Logger Debug Message') Logger.info ('Logger Info Message') logger.warning ('Logger warning message') Logger.error ('Logger error message') logger.critical ('Logger Critical Message')
Python: Common Module II