Python Module Learning 2

Source: Internet
Author: User

(1) Configparse module How to create the following configuration file[DEFAULT]Serveraliveinterval =Compression = yesCompressionLevel = 9ForwardX11 = yes [bitbucket.org]User = HG [topsecret.server.com]Port = 50022ForwardX11 = noImport Configparserconf = configparser. Configparser ()#直接创建conf [' DEFAULT '] = {' Serveraliveinterval ': ' A ', ' Compression ': ' Yes ', ' compressionlevel ': ' 9 ', ' ForwardX11 ': ' Yes ' } conf[' bitbucket.org ' = {}conf[' bitbucket.org ' [' User '] = ' HG ' conf[' topsecret.server.com '] = {}  Topsecret = conf[' topsecret.server.com ']topsecret[' Host Port ' = ' 50022 '  topsecret[' ForwardX11 '] = ' no '   conf[' DEFAULT ' [' ForwardX11 '] = ' yes '  with open (' Conf.ini ', ' W ') as Conf_file:conf.write (conf_file)  #----- ---------------Read Conf.read (' Conf.ini ', encoding= ' UTF8 ')    f = Conf.sections () print (f) [' bitbucket.org ', ' Topsecret.server.com '] d = conf.options (' bitbucket.org ') print (d) print (conf.default_section)   #? Found no print? How to read the default Default print (list (conf[' topsecret.server.com '].values ())) #取值和字典类似 [' 50022 ', ' no ', ' I ', ' yes ', ' 9 ']  #当自定义section和默认section时有相同的值时, which is to remove the value of the part that is Custom  if ' serveraliveinterval ' in conf[' default ']:    #也可以判断摸个值是否存在print (' yes ') else:print (' no ')   ############ #增conf. add_section(' groups ') conf[' groups '] = {' name ': ' Alex ', ' age ': '}with ' open (' Conf.ini ', ' r+ ', encoding= ' UTF8 ') as File:conf.write ( File) ######### #改conf. Set (' Groups ', ' age ', ' Conf.write ') (Open (' Conf.ini ', ' r+ ')) ########## #删除内容 option is to delete a value under a series, section is to delete a portion of the file under the Conf.read (' Conf.ini ') conf.remove_option (' groups ', ' name ') conf.write (open (' Conf.ini ', ' r+ ')) conf.remove_section (' groups ') conf.write (open (' Conf.ini ', ' r+ '))   (2) Hashlib module import HASHLIBM = Hashlib.md5 () m.update (b ' Hello ') print (m.digest)  hash = hashlib.sha256 () hash.update (' admin ') print ( Hash.hexdigest ())   (3) subprocess module can interact with the operating system three ways to execute Commands subprocess.run ()     #官方推荐subprocess. Call () Subprocess. Popen ()   #上面各种方法的底层封装标准写法 >>> subprocess.run ([' DF ', '-H '],stderr=subprocess. Pipe,stdout=subprocess. Pipe,check=true) Related to piping | command notation >>> subprocess.run (' Df-h|grep  disk1 ', shell=true) #将接将该条命令交给系统去处理 >>> a=subprocess.call ([' ls ', '-l '])   (4) logging Module (reference) FATAL-a critical system-level error that causes the program to exit, is unrecoverable, and when an error occurs, the system administrator needs to intervene immediately, Use with caution。 ERROR-run-time exceptions, as well as unexpected errors, need to be handled immediately, but less urgent than fatal, which affects the correct execution of the program when an error occurs. It is important to note that these two levels belong to the service's own error, requiring administrator intervention, and the user input error does not fall into this category. WARN-run-time condition other than expected indicates that the system may be having problems. For those who are not yet wrong, but not in time to deal with the situation will become wrong, can also be remembered as warn, such as disk too low. Info-meaningful event information that logs the normal running state of a program, such as receiving a request for successful execution. By viewing info, you can quickly locate Warn,error, FATAL. Info should not be too much, usually not more than 10% of trace. DEBUG-Details about the process at the time the program runs and the state of the current variable. Trace-more detailed tracking information. Debug and trace These two specifications are defined by the project group itself, through which you can view the execution of each step of an operation, you can accurately locate what kind of operation, what kind of parameters, what order causes the occurrence of a certain error mainly divided into four parts:
    • Loggers: Provides an interface that the application uses directly
    • Handlers: Upload loggers generated logs to the specified location
    • Filters: Filtering the output log
    • Formatters: Control output format
Log level when it ' s used
level Numeric value
DEBUG Detailed information, typically of interest O nly when diagnosing problems.
INFO Confirmation that things is working as expected.
WARNING a an indication that something unexpected happened, or indicative of Some problem in the near future (e.g "Disk space low"). The software is still working as expected.
ERROR + Due to a more serious problem, the software have not been able to perf ORM some function.
CRITICAL + A serious error, indicating the program itself could be unable To continue running.

#打印在控制台上 Import logginglogging.warning (' use error ') logging.critical (' Sever are down ') logging.info (' 111 ') Logging.debug (' 222 ') logging.error (' 333 ') #记录在文件中logging. Basicconfig (filename= ' Logging_test.log ', level=logging. info,format= '% (asctime) s:% (levelname) s:% (message) s ', datefmt= '%y-%m-%d '%i:%m:%s '%p ') #文件配置logging. Warning (' Lower power Action ') logging.info (' Use error ') Logging.debug (' Sever are down ') #即可以记录在文件中也可以在控制台中 # 1. Generate Logger Objects # 2. Generate Handler Objects # 2.1 Bind the handler object to the logger # 3. Generate Formatter Objects # 3.1 Generated Formatter object binding handler objectLogger = Logging.getlogger (' MySQL ') logger.setlevel (logging. DEBUG) #设置级别s = logging. Streamhandler () #屏幕handler对象s.setlevel (logging.info) #设置屏幕输出级别 f = logging. Filehandler (' Web.log ') #文件handler对象F.setlevel (logging. DEBUG) #s设置文件级别 Logger.addhandler (s) logger.addhandler (f) s.setformatter ('% (asctime) s:% (levelname) s:% (message) s ') F.setformatter ( '% (asctime) s:% (name) s:% (message) s ')

Python Module Learning 2

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.