Python Development Foundation DAY12 Module 2

Source: Internet
Author: User
Tags serialization

SYS module

The SYS module provides a series of variables and functions for the Python runtime environment.

1 #重点记忆2 sys.argv           #命令行参数List, the first element is the program itself path 3 sys.exit (n)        #退出执行的程序未见, exit normally exits (0), different from the loop break out of the Loop 4 Sys.path           #返回模块的搜索路径, initialize using the value of the PYTHONPATH environment variable 5 6 #一般7 sys.platform       #返回操作系统平台名称8 sys.version        #获取Python解释程序的版本信息9 Sys.maxint         #最大的Int值

Detailed Description:

sys.argv Method: Returns a list of command-line actions, simulating SQL login code

1 res=sys.argv 2 Print (RES) 3 username=res[2] 4 Password=res[4] 5 if res[1] = = '-U ' and res[3] = = '-P ': 6     if username = = ' Bob ' and password = = ' 123 ': 7         print (' loging successful ') 8 else:9     print (' Not formatted ') "Ten-one-cmd-call" C:\Users\Mr.chai \desktop\pythonproject\ Note \2017.6.22>python module 2.py-u bob-p 12313 [' Module 2.py ', '-u ', ' Bob ', '-P ', ' 123 '] #sys. argv return Value 14 Loging Successful

Sys.path: Returns the search path for the module, initialized with the value of the PYTHONPATH environment variable

1 #pycharm下执行2 Print (Sys.path) 3 output results: 4 [' c:\\users\\mr.chai\\desktop\\pythonproject\\ note \\2017.6.22 ', ' c:\\users\\ Mr.chai\\desktop\\pythonproject ', ' c:\\python36\\python36.zip ', ' c:\\python36\\dlls ', ' C:\\Python36\\lib ', ' C:\\ Python36 ', ' c:\\python36\\lib\\site-packages ']5 6 #cmd下执行7 C:\Users\Mr.chai\Desktop\PythonProject\ notes \2017.6.22> Python module 2.py8 [' c:\\users\\mr.chai\\desktop\\pythonproject\\ note \\2017.6.22 ', ' c:\\python36\\python36.zip ', ' C:\\ Python36\\dlls ', ' c:\\python36\\lib ', ' c:\\python36 ', ' c:\\python36\\lib\\site-packages ']

Pycharm executed under the ' C:\\users\\mr.chai\\desktop\\pythonproject ' is pycharm to add, to cmd downward use as the quasi

Find the module priority: The Built-in module (the directory under the Python interpreter)---third-party modules and custom modules, will be unified according to a path to find (execution of the file or import will add the directory to Sys.path, default added to the front)

When importing a custom module, the module name and the third-party module conflict under the Python interpreter will take precedence over the current Import custom module catalog file.

Built-in modules: sys, time, OS module (not quite verified for testing)

When a custom module needs to be called across directories, it is necessary to manually add the directory of the module to be called under the called py file:

1 sys.path.append (' Module path ')

Logging module

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.

The default log is output to the current screen terminal

1 Import Logging  2 logging.debug (' Debug Message ')  3 logging.info (' info message ')  4 logging.warning (' Warning message ')  5 logging.error (' Error message ')  6 logging.critical (' Critical message ')  

Log format configuration (this configuration is not recommended):

1 Import Logging   2 logging.basicconfig (level=logging. DEBUG,  #默认级别设置 3                     format= '% (asctime) s% (filename) s[line:% (lineno) d]% (levelname) s% (message) s ',  #日志输出格式 4                     datefmt= '%a,%d%b%Y%h:%m:%s ',  #时间输出格式 5                     filename= '/tmp/test.log ',  #日志输出目录 6                     filemode= ' W ') c9/> #文件写入权限, A or W 7    8 logging.debug (' Debug message ')   9 logging.info (' info message '),  logging.warning ( ' Warning message ')  logging.error (' error message ')  logging.critical (' critical message ')

Configuration parameters:

The 1 logging.basicconfig () function can change the default behavior of the logging module through specific parameters, the available parameters are: 2  3 filename: Creates a filedhandler with the specified file name so that the logs are stored in the specified files. 4 FileMode: File open mode, use this parameter when filename is specified, the default value is "a" can also be specified as "W". 5 format: Specifies the log display format used by handler. 6 DATEFMT: Specifies the date time format. 7 level: Set Rootlogger (which will explain the concept in the back) 8 stream: Creates a streamhandler with the specified stream. You can specify the output to Sys.stderr,sys.stdout or the file (F=open (' Test.log ', ' W ')), and the default is Sys.stderr. If you list both the filename and stream two parameters, the stream parameter is ignored. 9 Possible formatting strings in the format parameter: one% (name) s logger name (Levelno) s number form the log level of the log level (LevelName) s in text form (pathname) s The full pathname of the module that invokes the log output function, may not have the file name of the module that is called the log output function (filename), and the module name of the call log output function is 18% (FuncName) s called the function name of the log output function. Lineno) d The code line where the statement that called the log output function is located (created) f The current time, the floating-point number with the UNIX standard representation time represents the 21 (relativecreated) d output of the log information, and the milliseconds since the logger was created ( Asctime) s current time as a string. The default format is "2003-07-08 16:49:45,896". The comma is followed by a milliseconds (thread) d thread ID. There may not be a percent (ThreadName) s thread name. There may not be a percent (process) d process ID. Messages that may not have a user output of (message) s

Log Object configuration: (Recommended log Configuration method)

1 #使用logger对象 2 Logger_obj=logging.getlogger () 3  4 # Screen output stream 5 cp=logging. Streamhandler () 6 # File output stream 7 fp=logging. Filehandler (' Logger.txt ') 8  9 #定义格式对象10 formatter=logging. Formatter ('% (asctime) s% (filename) s[line:% (lineno) d]% (levelname) s% (message) s ') One #设置格式13 cp=cp.setformatter ( Formatter) Fp=fp.setformatter (formatter) #定义默认级别17 logger_obj.setlevel (logging. DEBUG) #输出流定义20 Logger_obj.addhandler (FP) Logger_obj.addhandler (CP) Logger_obj.debug (' Log info ') Logger_ Obj.info (' log error ') logger_obj.warning (' log error ') of Logger_obj.error (' log error ') logger_obj.critical (' Log Error ')

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.

Serialization module

The process of turning an object (variable) from memory into a storage or transfer is called serialization.

The serialization module used internally by Python is the Pickle module, and the JSON module is used between different programming languages

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:

1 #----------------------------serialization of 2 import JSON 3 dic={' name ': ' Alvin ', ' age ': at $, ' sex ': ' Male '} 4 print (Type (DIC)) #< Class ' Dict ' > 5 data=json.dumps (DIC) 6 print ("Type", type (data)) #<class ' str ' > 7 print ("Data", data) 8 F=open (' Serialized object ', ' W ') 9 f.write (data)  #等价于json. Dump (dic,f), equivalent to opening the file and writing the file two Steps f.close () #----------------------------- Deserialization <br>13 Import json14 f=open (' serialized object ')-New_data=json.loads (F.read ()) #  is equivalent to Data=json.load (f), Open file and read data print (type (new_data))

Pickle Module

1 # #----------------------------serialization 2 import pickle 3 dic={' name ': ' Alvin ', ' age ': +, ' sex ': ' Male '} 4 print (Type (DIC)) # <class ' Dict ' > 5 j=pickle.dumps (DIC) 6 print (Type (j)) #<class ' bytes ' > 7 f=open (' serialized object _pickle ', ' WB ') # Note is that W is written STR,WB is written bytes,j is ' bytes ' 8 f.write (j)  #-------------------equivalent to Pickle.dump (dic,f) 9 f.close () #------- ------------------deserialization of import pickle13 F=open (' serialized object _pickle ', ' RB ') + data=pickle.loads (F.read ()) #  equivalent to Data= Pickle.load (f) Print (data[' age ')    

Python Development Foundation DAY12 Module 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.