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
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)
The resulting file
= * = 9 = yes = HG = 50022 = no
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') #增加sectionconfig. Remove_section ('bitbucket.org') #删除一个sectionconfig. 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 Simple function type
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') #低级别的 sub-error message Logging.info ('Info Message') #正常信息logging. Warning ('warning Message') #警告信息logging. Error ('error Message') #错误信息logging. Critical ('Critical Message') #高级别的, critical error information
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
Logger 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')
The logging library provides multiple components: Logger, Handler, Filter, Formatter. The Logger object provides an interface that the application can use directly, handler sends logs to the appropriate destination, and filter provides a way to filter the log information formatter specify the log display format. Alternatively, you can pass: logger.setlevel (logging. Debug) Setting levels, of course, can also be
Fh.setlevel (logging. Debug) to set a level on a file stream.
Python--configparser and Logging Modules