A. SYS module
1 sys.argv command line argument list, the first element is the program itself path 2 sys.exit (n) exit the program, exit normally exits (0)3 sys.version get version information for Python interpreter 4sys.maxint Maximum int value 5 Sys.path Returns the search path for the module, initializes with the value of the PYTHONPATH environment variable 6 sys.platform returns the operating system platform name
Two. Logging module
2.1 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:
Import Logging 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- -- , -: the: $,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
2.2 Logger Object Configuration
Import Logginglogger=Logging.getlogger () # Create a handler for writing to the log file FH= Logging. Filehandler ('Test.log'# Create another handler for output to the console ch=logging. Streamhandler () Formatter= Logging. Formatter ('% (asctime) s-% (name) s-% (levelname) s-% (message) s') Fh.setformatter (formatter) ch.setformatter (formatter) Logger.addhandler (FH) # Logger objects can be added with multiple FH and ch objects logger.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) set the level.
three. Serialization Module
What is serialization?
The process of changing an object (variable) from memory to a storage or transfer is called serialization, and in Python it is called pickling, which is also called serialization,marshalling,flattening in other languages, and so on. After serialization, the serialized content can be written to disk or transferred over the network to another machine. In turn, re-reading the variable contents from the serialized object into memory is called deserialization, i.e. unpickling.
JSON module
If we are going to pass objects between different programming languages, we have to serialize the object into a standard format, such as XML, but the better way is to serialize it to JSON, because JSON represents a string that can be read by all languages, easily stored to disk, or transmitted over a network. JSON is not only a standard format, but also faster than XML, and can be read directly in the Web page, very convenient.
JSON represents a subset of objects in the standard JavaScript language, and the JSON and Python built-in data types correspond to the following:
Import Jsoni=Tens='Hello'T=(1,4,6) L=[3,5,7]d={'name':"Yuan"}JSON_STR1=json.dumps (i) json_str2=Json.dumps (s) json_str3=json.dumps (t) JSON_STR4=json.dumps (l) JSON_STR5=Json.dumps (d) print (JSON_STR1) #'Ten'print (JSON_STR2) #'"Hello"'print (JSON_STR3) #'[1, 4, 6]'print (JSON_STR4) #'[3, 5, 7]'print (JSON_STR5) #'{"name": "Yuan"}'View Code
Python's use in text:
#----------------------------Serialized Import Jsondic={'name':'Alvin',' Age': at,'Sex':'male'}print (Type (DIC)) #<class 'Dict'>Data=json.dumps (DIC) print ("type", type (data)) #<class 'Str'>Print ("Data", data) F=open ('Serializing Objects','W') F.write (data) #-------------------equivalent to Json.dump (dic,f) f.close () #-----------------------------deserialization <br>Import jsonf=open ('Serializing Objects') New_data=json.loads (F.read ()) # equivalent to Data=json.load (f) Print (type (new_data))
Pickle Module
##----------------------------serialized import Pickle dic={'name':'Alvin',' Age': at,'Sex':'male'} print (Type (DIC)) #<class 'Dict'>J=pickle.dumps (DIC) print (Type (j)) #<class 'bytes'>F=open ('Serialized Object _pickle','WB') #注意是w是写入str, WB is written bytes,j is'bytes'F.write (j) #-------------------equivalent to Pickle.dump (dic,f) f.close () #-------------------------deserialization Import Picklef=open ('Serialized Object _pickle','RB') Data=pickle.loads (F.read ()) # equivalent to Data=pickle.load (f) Print (data[' Age'])
Shelve module
import shelve F= Shelve.open (r'Shelve.txt') # f['Stu1_info']={'name':'Alex',' Age':' -'}# f['Stu2_info']={'name':'Alvin',' Age':' -'}# f['School_info']={'website':'oldboyedu.com',' City':'Beijing'}### f.close () print (f.Get('Stu_info')[' Age'])
The shelve module is simpler than the Pickle module, with only one open function, which returns a dictionary-like object, readable and writable; key must be a string, and the value can be a data type supported by Python
DAY12: Common Module II (SYS,LOGGING,JSON)