First, the module
Module:
A set of functions, in Python a py file is a module, the module name is the file name of the py file;
Benefits of the module:
1. Reduce duplication of code
2. Take doctrine
Define the module:
is to create a py file;
Using modules:
Keywords: import
Usage: Import module name (do not add py suffix)
Note that the execution file is your current logic program, and the module file is the file you use to invoke the function;
First Import module:
1. Create a namespace for a module
2. Execute the module file and store the name of the module file in the Created module namespace
3. When the execution file gets a module name, the module name points to the module name in the module namespace
Emphasis: When the module name is imported for the first time, the module contents will be imported into the memory space, when the same file is used to guide the module name is the first time to import the module file in memory space, will not import the module file;
Functions within the calling module:
Use the module name. function name ()
Attention:
The execution of the function in the module always takes the module's own name space as the standard;
That is, the function of the module is called the value of the module, the modification is also the value within the module, does not affect the current execution of the file;
Alias the module:
Keyword as
Defined:
Import module name as the module name to be defined;
Use:
1. Module name is too long, the module name definition is shorter, less cumbersome
2. For example, there are two modules, two modules have the same function name, but the function effect is different, this time you can change the two module names to the same module name,
With an input to determine which function you want to import, which module name you entered, which module is the effect of the function, module name (modified) and the function name unchanged,
, the use of what function depends on the name of the module you entered, the other code does not need to change, after the modification only needs to add a more judgment module name can be;
Importing multiple modules (not recommended)
Import Module name 1, module name 2, module name 3
Recommended or multi-line import
The second type of import:
Keyword from
From Module name Import function name 1, function name 2, function name 3
First import:
1. Create a namespace for a module
2. Execute the module file and store the name of the module file in the Created module namespace
3. In the current namespace can directly get the name of the module, can be used directly, without adding any prefix
Note: This happens because there is no module name. function name, if there is the same name as the module name in the current execution file, the function name (variable name) within the current file will be executed.
So be aware that you cannot take the same name as the module function;
Multiple calls:
Key words: *
From Module name Import *
* Replace the name of all functions that can be called;
Note: Because some features are commonly used, some functions are not commonly used, the designer of the module will generally control the name of the module that can be called;
Keyword: __all__=[]
__all__=[function name 1, function Name 2 ....]
After the limit, * can be called only the function name within all;
Test module function:
Keyword: __name__
The value of the __name__
1. In the case of direct execution of the document equals __main__
2. Equals the module name in case the file is imported
That is, you can use the __name__ to determine whether to directly execute the test function, or import
if __name__ = = ' __main__ ':
#代码块
Print (' re-enter the function you want to test in the code block ')
The search path for the module
Sys.path: The folder where the current execution file is located; see only the first path;
You can use print (Sys.path) to output the path in the terminal, the first one is the folder where the current execution file resides
The order in which the modules are found:
1. Memory space
2. Built-in space
3.sys.path Path
Sys.modules: Modules that are already imported in the current memory
Print (sys.modules): All imported modules in the terminal output memory
Add a path in Sys.path
Sys.path.append (path to add)
For example, you put the module file in a different folder, Sys.path is only the current folder, this time with append to put the folder of the module to add the path to Sys.path,
This allows the module to be found in the Sys.path folder, which can be called
Software Development Catalog Specification
Path: Assign a path with a constant name, followed by
Constant path name =r ' path '
Common directory: (current level with this directory is enough)
ATM: folder, the name of the project to be used to store all files and folders related to the project
Readme: File for introduction of program functions
Bin: folder, just put the startup file
Start: File, startup file
conf: folder, for storing configuration files
Settings: File name, configuration file
Core: folder, storing kernel logic
SRC: file name, business core logic files
db: folder for storing data files
DB: File name, for storing data
Lib: a folder for storing commonly used tools, i.e. module files
Common: File name, common function files, commonly used module files
Log: folder to store file logs
Access.log: File name, log file
The root directory of the project should be added to the environment variable;
Just like the ATM project above:
The root directory is the ATM directory, you need to invoke what function, in the root directory can be found
Fetch directory:
Os.path.dirname (__file__): Take the directory where the current file resides
Os.path.dirname (Os.path.dirname (__file__)): Take the directory that is currently located in the file directory
And so on, take the first few layers to write a few paragraphs, followed by a convenient method, this method is for reference only
Then assign the path you need to a constant, and call the constant name directly when you need to call it later.
You do not have to enter a fixed directory to restrict the program
For example, Sys.path.append (Os.path.dirname (__file__)): Joins the current path directly
The second method: recommended
Os.path.normpath (Os.path.join (
__FILE__,
‘..‘,
‘..‘
))
Logging module
Debug: Represents debug information, Level 10
Info: Represents normal operation information, level 20
Warning: Represents a warning message, level 30
Errot: Represents error message, level 40
Critical: Represents crash information, level 50
What level is set and what level of information is printed
Logging module Templates
"""
Logging configuration
"""
#定义日志文件路径
#把日志路径赋予一个变量
Log_path=r ' A3.log '
# define three log output formats to start
#把自己定义的个数赋予一个变量用于后面的调用
Standard_format = ' [% (asctime) s][% (threadname) s:% (thread) d][task_id:% (name) s][% (filename) s:% (Lineno) d] ' \
' [% (levelname) s][% (message) s] ' #其中name为getlogger指定的名字
Simple_format = ' [% (LevelName) s][% (asctime) s][% (filename) s:% (Lineno) d]% (message) s '
Id_simple_format = ' [% (LevelName) s][% (asctime) s]% (message) s '
# log Config dictionary
Logging_dic = {
' Version ': 1,
' Disable_existing_loggers ': False,
#多个日志格式, cannot be changed
' formatters ': {
#日志格式名, can be changed, the name means to hit the terminal
' Standard ': {
#日志格式: variable name in the format defined above
' Format ': Standard_format
},
#这个名字的意思是往文件打
' Simple ': {
' Format ': Simple_format
},
},
#过滤, it's no use, you can ignore
' Filters ': {},
#定义日志输出的格式: File or terminal, cannot be changed
' Handlers ': {
#打印到终端的日志名, you can change
' Console ': {
#定义日志级别, cannot be changed: Log level, can be changed to debug/info/warning/errot/critical
' Level ': ' DEBUG ',
#定义日志输出格式, cannot be changed
' class ': ' Logging. Streamhandler ', # Print to screen
#绑定格式, cannot be changed: The specific format is changed according to the format defined above
' Formatter ': ' Simple '
},
#打印到文件的日志, collect logs of info and above
' Default ': {
' Level ': ' DEBUG ',
' Class ': ' Logging.handlers.RotatingFileHandler ', # Save to File
' Formatter ': ' Standard ',
#日志写到哪个文件: variable name, this variable we have in the above to give the path
' filename ': log_path, # log file
#规定日志切分大小, in bytes
' MaxBytes ': 1024*1024*5, # log size 5M
#规定日志切分后保存的日志次数
' Backupcount ': 5,
#日志文件编码
' Encoding ': ' Utf-8 ', # Log file encoding, no need to worry about Chinese log garbled
},
},
#产生日志, and the name of the pass, the name NULL for the default
' Loggers ': {
#logging. GetLogger (__name__) Get the logger configuration
‘‘: {
#把日志丢给谁, the log name defined above the top of the list
' Handlers ': [' Default ', ' Console '], # This adds the two handler defined above, that is, the log data is written to the file and printed to the screen
#设置级别, two levels, same level as above
' Level ': ' DEBUG ',
#向父级传递, it's usually closed.
' Propagate ': False, # Up (higher level of logger) pass
},
},
}
Import logging
Import Logging.config
#加载上方定义的字典
def get_logger (name):
#让logging模块从字典里加载配置
Logging.config.dictConfig (logging_dic) # Import the logging configuration defined above
#拿到logging名, because the above logging name is empty, so here with __name__, if the above definition of real names, use the above definition of real
Logger = Logging.getlogger (name) # generates a log instance
Return Logger # Record the running status of the file
#用来测试是否在当前文件执行
if __name__ = = ' __main__ ':
Get_logger ()
What is serialization:
The process of changing an object (variable) from memory into a stored or transportable procedure is called serialization;
Why you should have serialization:
1. Persistent Save State
2. Cross-platform data interaction
JSON module
JSON can only handle dictionaries, lists, strings, numbers, bool, NULL types
Inside the JSON are double quotes
Serialization: In-memory data structures--turns into an intermediate format (string)--stored in a file
Keyword: json.dump ()
Usage: Json.dump (requires serialized value, open file's variable name)
Deserialization: File--Read intermediate format (string)--turn into in-memory data structure
W Write mode only
Keyword: json.load
Usage: json.load (variable name for open file)
Pickle Module
Pickle can convert all types, but can only be used in Python
Serialization: In-memory data structures--turns into an intermediate format (string)--stored in a file
Keyword: pickle.dump ()
Usage: Pickle.dump (requires serialized value, open file's variable name)
Deserialization: File--Read intermediate format (string)--turn into in-memory data structure
W Write mode only
Keyword: pickle.load
Usage: pickle.load (variable name for open file)
OS Module
Os.path.abspath (path) returns the absolute path normalized by path
Os.path.dirname (path) returns the directory of path. is actually the first element of Os.path.split (path)
Os.path.basename (Path) returns the last file name of path. If path ends with a/or \, then a null value is returned. The second element of Os.path.split (path)
Os.path.exists (path) If path exists, returns true if path does not exist, returns false, does not distinguish between folders
Os.path.isabs (path) returns True if path is an absolute path
Os.path.isfile (path) returns True if path is a file that exists. otherwise returns false
Os.path.isdir (path) returns True if path is a directory that exists. otherwise returns false
Os.path.getsize (path) Statistics file size in bytes
Os.path.join (' A ', ' B ', ' C.txt ') is returned after combining multiple paths, and the parameters before the first absolute path are ignored
Do not write path characters
Os.path.normpath (path) normalize the path, put the inside of the slash the same, ... (.. Returns the previous layer symbol) execution, etc.
The absolute path used to take the required:
Python tour. Fourth chapter: Modules and Packages. Summary (unfinished treatment)