Two common modules in Python

Source: Internet
Author: User

Explanation of the Log module

1 Python uses the logging module to log logs involving four main classes, which are best used in the official documentation:2 3 logger provides an interface API that the application can use directly;4 handler sends the log record (created by logger) to the appropriate destination output;5 Formatter determining the final output format of the log record6 Filter provides a fine-grained device to determine which log record to output;7 8 Logger9 Each program obtains a logger before outputting the information. Logger usually corresponds to the module name of the program,Tensuch as the Chat tool graphical interface module can get its logger:log=Logging.getlogger ("Chat.gui") One  A You can also bind handler and filters - Logger.setlevel (LEL): Specifies the lowest log level, and the level below LEL is ignored. Debug is the lowest built-in level, critical is the highest - Logger.addfilter (filt), Logger.removefilter (filt): Add or remove the specified filter the Logger.addhandler (HDLR), Logger.removehandler (HDLR): Add or remove the specified handler - multiple handler can be attached to each logger. Next, let's introduce some common handler: - logging. Streamhandler uses this handler to output information to any file object, such as Sys.stdout or Sys.stderr.  - logging. Filehandler and Streamhandler are similar for outputting log information to a file. But Filehandler will open this file for you . + Logging.handlers.RotatingFileHandler - This handler is similar to the filehandler above, but it can manage the file size.  + when the file reaches a certain size, it automatically renames the current log file and then creates a new log file with the same name to continue the output.  A For example, the log file is Chat.log. When the chat.log reaches the specified size, atRotatingfilehandler automatically renamed the file to Chat.log.1.  -However, if chat.log.1 already exists, the Chat.log.1 will be renamed to Chat.log.2 first......  - Finally, re-create the Chat.log and continue to output the log information.  - function Format: Rotatingfilehandler (filename[, mode[, maxbytes[, Backupcount]]) maxbytes Maximum length backupcount number of files reserved - Logging.handlers.TimedRotatingFileHandler - This handler is similar to Rotatingfilehandler, but it does not determine when the log file is recreated by judging the file size. in instead, a new log file is created automatically at a certain time interval. The process of renaming is similar to Rotatingfilehandler, - However, the new file is not an additional number but the current time.  to its function is: timedrotatingfilehandler (filename [, when [, interval [, Backupcount]]) +when="s" seconds calculate interveal interval backupcount number of files reserved -s seconds M min h hours d days W per week (interval==0 o'clock on behalf of Monday) midnight every morning the Formatter Components * The formatter of the log is a separate component that can be combined with handler $FH = logging. Filehandler ("Access.log")Panax NotoginsengFormatter = logging. Formatter ('% (asctime) s-% (name) s-% (levelname) s-% (message) s') -Fh.setformatter (Formatter)#bind the Formmater to the FH. the If you want to filter the log content, you can customize a filter + classIgnorebackuplogfilter (logging. Filter): A     """ignore logs with DB backup""" the     defFilter (self, record):#fixed notation +         return   "DB Backup"  not inchrecord.getmessage () -  $ #Note that the filter function returns TRUE or False,logger determines whether this log is output based on this value $  - #then add this filter to the logger - #Logger.addfilter (Ignorebackuplogfilter ())
Description Parsing 

 

Import loggingfrom Logging Import handlers# set an output to Handlerlog_p_handler = logging on the screen. Streamhandler () # defines the Handlerlog_f_handler = logging of an input file. Filehandler ("Xx.log", encoding= "UTF8") # This is the example of that log truncation, truncated by length log_f_handler_1 = handlers. Rotatingfilehandler ("Xxx.log", maxbytes=10, backupcount=2, encoding= "UTF8") log_f_handler_1.setlevel (logging. WARNING) Log_f_handler.setlevel (logging. WARNING) # handler defines a log level log_p_handler.setlevel (logging.info) # for access to a file handler define a log level fm_p = logging. Formatter ("% (asctime) s-% (levelname) s->% (message) S", datefmt= "%y-%m-%d%i:%m:%s") # defines two formats Fm_f = logging. Formatter ("% (asctime) s-% (filename) s-% (levelname) s->% (message) S", datefmt= "%y-%m-%d%i:%m:%s") # Add format to Handler in Log_f_handler.setformatter (Fm_f) log_f_handler_1.setformatter (Fm_f) log_p_handler.setformatter (fm_p) Log = Logging.getlogger ("Test") # generates a log interface # adds its own defined handler to log Log.addhandler (Log_p_handler) Log.addhandler (log_f_ Handler) Log.addhandler (log_f_handler_1) # set log global logging level if not set the default warning level LOg.setlevel (Logging.info) log.info ("INFO log") log.warning ("Warn log") log.debug ("Debug Log") 

  

The Subproess module provides a unified module to implement calls to system commands or scripts

# Three ways to execute commands # Subprocess.run (*popenargs, Input=none, Timeout=none, Check=false, **kwargs) #官方推荐 # subprocess.call (* Popenargs, Timeout=none, **kwargs) #跟上面实现的内容差不多, another way # #subprocess. Popen () #上面各种方法的底层封装 # Run's standard notation import subprocesssubprocess.run ([' DF ', '-h '], stderr=subprocess. PIPE, Stdout=subprocess. Pipe, Check=true) # parameter resolution: [' DF ', '-h '] List execution command subprocess will be stitched together stdout standard output =pipe pipe character Check True error # also can be with shell=true so you can  With direct write command: Subprocess.run (' Df-h|grep disk1 ', shell=true) # shell=true means that this command is delivered directly to the system and does not require Python to parse # Execute command, return command execution state, 0 or Non 0retcode = Subprocess.call (["LS", "-L"]) # Execute command, if command result is 0, return normally, otherwise throw exception subprocess.check_call (["LS", "-L"]) # 0# receive string Format command , returns the tuple form, the 1th element is the execution state, and the 2nd is the command result subprocess.getstatusoutput (' Ls/bin/ls ') # (0, '/bin/ls ') # Receive string Format command, and returns the result Subprocess.getoutput (' Ls/bin/ls ') # '/bin/ls ' # executes the command and returns the result, note that the result is returned, not printed, and the following example returns to Resres = Subprocess.check_output ([' ls ', '-l ']) # res= B ' Total 0\ndrwxr-xr-x-Alex Staff 408 2 11:05 oldboycrm\n ' # Popen will not wait for command execution to return results but return a handle to a call PO ll () method can be checkedThe specified state of a = subprocess. Popen (' Sleep ', shell=true, stdout=subprocess. PIPE) #这里还有其他方法 will not repeat it. # a.wait () A.kill () a.pid () # a.send_signal () a.terminate ()
Hashlib: For cryptographic related operations, instead of MD5 module and SHA module, mainly provides SHA1, SHA224, SHA256 , SHA384, SHA512, MD5 algorithm
Import hashlib# is used for cryptographic related operations, 3.x replaces the MD5 module and the SHA module, mainly provides SHA1, SHA224, SHA256, SHA384, SHA512, MD5 algorithm m=hashlib.md5 () m.update ( Bytes ("I", encoding= "UTF8")) m.update (b ' It is Me ') print ("Binary", M.digest ()) print ("Hex", M.hexdigest ()) # Although the above encryption algorithm is still very strong, but the time has the flaw, namely: through the collision library can reverse the solution. Therefore, it is necessary to add a custom key to the encryption algorithm to do encryption. Print ("". Center ("*")) M1=hashlib.md5 (bytes ("Encrypt on Build", encoding= "UTF8")) m1.update (bytes ("I", encoding= "UTF8")) M1.update (b ' It is Me ') print ("Binary", M.digest ()) print ("Hex", M.hexdigest ())

RE module: The regular expression is the string matching rules, in most programming languages have corresponding support, Python corresponding module is re

'.'default match any character except \ n, if flag Dotall is specified, matches any character, including line break#The ' ^ ' matches the beginning of the character, and if you specify the flags MULTILINE, this can also be matched on (r "^a", "\nabc\neee", Flags=re. MULTILINE)#' $ ' matches the end of the character, if specified by flags MULTILINE, Re.search (' foo.$ ', ' foo1\nfoo2\n ', re. MULTILINE). Group () will match to Foo1#' * ' matches the character before the * number 0 or more times, Re.search (' A * ', ' aaaabac ') result ' aaaa '#' + ' matches the previous character 1 or more times, Re.findall ("ab+", "Ab+cd+abb+bba") results [' AB ', ' ABB ']#'? ' Match the previous character 1 or 0 times, re.search (' B? ', ' Alex '). Group () match B 0 Times#' {m} ' matches the previous character m times, Re.search (' b{3} ', ' Alexbbbs '). Group () match to ' BBB '#' {n,m} ' matches the previous character N to M times, Re.findall ("ab{1,3}", "ABB ABC abbcbbb") Results ' ABB ', ' AB ', ' ABB ']#' | ' Match | left or | Right character, re.search ("abc| ABC "," ABCBABCCD "). Group () result ' ABC '#' (...) ' Group match, Re.search ("(ABC) {2}A (123|45)", "abcabca456c"). Group () Results for ' abcabca45 '# # #' \a ' matches only from the beginning of the character, Re.search ("\aabc", "ALEXABC") are not matched, equivalent to Re.match (' abc ', ' alexabc ') or ^#' \z ' matches the end of the character, same as $#' \d ' matches digital 0-9#' \d ' matches non-numeric#' \w ' match [a-za-z0-9]#' \w ' matches non-[a-za-z0-9]#' s ' matches whitespace characters, \ t, \ n, \ r, Re.search ("\s+", "Ab\tc1\n3"). Group () result ' \ t '# #' (? P<name>, ...) ' Group Matching Re.search (? P<province>[0-9]{4}) (? P<city>[0-9]{2}) (? P<BIRTHDAY>[0-9]{4}) "," 371481199306143242 "). Groupdict (" City " )#result {' Province ': ' 3714 ', ' City ': ' Bayi ', ' Birthday ': ' 1993 '}
Model Details

Import res = ' AB23CD121RF ' Res=re.match ("[0-9]", s) #从头开始匹配 match one on end print (res) res = Re.search ("[0-9]{2}", s) # match matches from all character matches An end of the print (RES) # object takes the value inside the group without an error, and the result needs to be judged if Res:print (Res.group ()) Else:print ("none!") Print (Re.findall ("[0-9]", s)) # match all matches and put it in the list print (Re.search (".", "AAA") # from the beginning to find any character returned to print (Re.search ("^a", "AA A ")) # equals match (' A ') print (Re.search (" ^ab "," Abaab ")) # equals match (' A ') print (Re.search (" ab+$ "," Abaabb ") # from the last search. Print at end of ABB (multiple B) (Re.search ("[a| A]lex "," Alexalex ")) #自己的理解就是拿着alex #或 Alex to find a match in the character to print (Re.search (" [a| A]lex "," Aaalex ")) s = ' 120980199612098769 ' #必须是字符匹配print (Re.search (" (\d{6}) (\d{4}) (\d{4}) ", s). Groups ()) # Group Matching print (Re.search (? P<province>\d{6}) (? P<year>\d{4}) (? P&LT;MOTHON&GT;\D{4}) ", s). Groupdict ()) F = open (" Contact. txt ", encoding=" GBK ") data = F.read () print (data) f.close () res = Re.findall ("(1\d{10})", data) # Mobile number print (res) s = "Alex22jack22rain33" Print (Re.split ("\d", s)) # split print in one format ( Re.split ("\d+", s)) s1= "Alex22jack22rain33#mock-oldboy" Print (Re.split ("\d+|#|-", S1) # The given character all matches successfully then returns the character otherwise 0# print (Re.fullmatch (' \[email  protected]\w+\. (com|cn|edu) ', ' [email protected] ') # Blur find the character that needs to be matched to replace print (Re.sub ("[\d+|#|-]", "_", S1)) s = ' 9-2*5/3+7/3*99/4* 2998+10*568/14 ' # Print (Re.split (' [\*\-/+] ', s)) #转义需要 \ to express print (Re.split (' [\*\-/+] ', S, maxsplit=2)) # Escape required \ to express maxspli T match before a few stops match # [' 9 ', ' 2 ', ' 5 ', ' 3 ', ' 7 ', ' 3 ', ' 99 ', ' 4 ', ' 2998 ', ' 10 ', ' 568 ', ' 14 ']

  

Two common modules in Python

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.