1. Module introduction
1. Definition:
Module: The essence is the python file ending in .py (file name: test.py, corresponding module name: test)
Used to logically organize python code (variables, functions, classes, logic: realize a function)
2. Syntax:
import statement
When the interpreter encounters an import statement, it will be imported if the module is in the current search path. The search path is a list of all directories that the interpreter will search first.
Import module:
call symbol:
From...import statement
Python's from statement allows you to import a specified part from the module into the current namespace. The syntax is as follows:
From...import statement *
It is also possible to import all the contents of a module into the current namespace, just use the following declaration:
This provides an easy way to import all items in a module. Use from...import * with caution.
The difference between import and from:
When import is used, add the prefix module.func(). It is equivalent to putting the module code in the current file and executing it again.
from can specify the required function or variable import.
The imported module and the current py file have the same function, which one will be called?
Because python is interpreted, the back covers the front.
from … import … as …
3. Import essence
Import essence:
The essence of importing a module is to interpret and execute a python file
Importing a package essentially explains the __init__.py file under the package
init.py
Package: The essence is a directory (must have a __init__.py file), used to logically organize modules
How to import the package?
**The essence of importing the package: **Execute the __init__.py file under the package
Import the modules under the package
The module under the package, such a call is wrong
Import the module in the __init__.py content
4. Path search and search path
The above mentioned are importing modules in the same level directory, if they are not in the same directory:
Import module_name actually finds the module_name.py file, if it is a file, it must have a path.
Importing a module is: find the location of the .py file, execute it again, and where can you find it? sys.path.
#See above: sys.path is
the current path in a list #, which is why the search module first searches from the current directory
os.path.abspath( file ) # The absolute path of the current file
os.path.dirname (os.path.abspath( file ))
#Get the directory name sys.path.append(): append to the end
#So: you can dynamically add the path to the first
sys.path.insert as follows
5. Import optimization
6. Prevent attribute import
If you don't want a certain module attribute to be imported by "from module import *", then you can add an underscore (_) to the attribute name you don't want to import. But if you import the entire module or you explicitly import a certain attribute, this method of hiding data will not work.
Second, the classification of modules
a: Standard library
b: Open source module-third-party module
c: custom module
3. Commonly used built-in modules
1. The os module
Used to provide system-level operations
2、time和datetime
In Python, there are usually several ways to express time:
Timestamp
Formatted time string
The tuple (struct_time) has nine elements in total.
Since Python's time module implementation mainly calls the C library, each platform may be different.
UTC (Coordinated Universal Time) is also Greenwich astronomical time, the universal standard time. It is UTC+8 in China. DST (Daylight Saving Time) is the daylight saving time.
Timestamp (timestamp): Generally speaking, the timestamp represents the offset in seconds from 00:00:00 on January 1, 1970. We run "type(time.time())" and the return is a float type. The functions that return the timestamp method mainly include time(), clock(), etc.
Tuple (struct_time) mode: struct_time tuple has 9 elements in total, and the functions that return struct_time mainly include gmtime(), localtime(), and strptime().
Time to timestamp
Formatted time string
Convert timestamp and tuple to time string
Time addition and subtraction
3. Random module
4. sys module
5. Shuil module
Advanced file, folder, copy, compressed package and other processing modules
6、ConfigParser
Used to operate a specific configuration, the name of the current module is changed to configparser in python 3.x version.
Look at the common document format of a lot of software as follows
What if you want to use python to generate such a document?
Generate
Read it out
Configparser add, delete, modify and check grammar
7, hashlib module
Used for encryption-related operations. In 3.x, the md5 module and sha module are replaced, mainly providing SHA1, SHA224, SHA256, SHA384, SHA512, MD5 algorithms, and hash encryption are all bytes type
Python also has a hmac module, which internally processes the keys and contents that we create and then encrypts them
8. Subprocess module
Calling subprocess.run(...) is the recommended and common method, which can meet the needs in most cases, but if you may need to perform some complex interactions with the system, you can also use subprocess.Popen(), the syntax is as follows:
Available parameters:
args:shell命令,可以是字符串或者序列类型(如:list,元组)
bufsize:指定缓冲。0 无缓冲,1 行缓冲,其他 缓冲区大小,负值 系统缓冲
stdin, stdout, stderr:分别表示程序的标准输入、输出、错误句柄
preexec_fn:只在Unix平台下有效,用于指定一个可执行对象(callable object),它将在子进程运行之前被调用
close_sfs:在windows平台下,如果close_fds被设置为True,则新创建的子进程将不会继承父进程的输入、输出、错误管道。 所以不能将close_fds设置为True同时重定向子进程的标准输入、输出与错误(stdin, stdout, stderr)。
shell:同上
cwd:用于设置子进程的当前目录
env:用于指定子进程的环境变量。如果env = None,子进程的环境变量将从父进程中继承。
universal_newlines:不同系统的换行符不同,True -> 同意使用
startupinfo与createionflags只在windows下有效 将被传递给底层的CreateProcess()函数,用于设置子进程的一些属性,如:主窗口的外观,进程的优先级等等
There are two types of commands entered by the terminal:
• 输入即可得到输出,如:ifconfig
• 输入进行某环境,依赖再输入,如:python
Examples of commands that require interaction
9, re-regular expression module
Commonly used regular expression symbols The
most common matching syntax
Group matching and group(), groups(), groupdict()
10. The logging module
Python's logging module provides a standard log interface, through which you can store logs in various formats. The logging logs can be divided into five levels: debug(), info(), warning(), error() and critical() , Let’s take a look at how to use it.
The simplest usage
Take a look at what these log levels mean
If you want to write the log to a file, it's also very simple
The level=loggin.INFO in the following sentence means that the log record level is set to INFO, that is, only logs that are INFO or higher than the log will be recorded in the file. In this example , The first log will not be recorded. If you want to record the debug log, just change the log level to DEBUG.
If you want to print the log on the screen and the file log at the same time, you need to understand a bit of complicated knowledge
11. JSON and pickle data serialization
str eval
Data serialization
json can only handle simple ones, common to all languages, and functions cannot be serialized by json
Pickle can serialize all data types in python
12. Shelve module
The shelve module is a simple k, v module that persists memory data through files, and can persist any python data format supported by pickle
13, xml processing module
XML is a protocol for data exchange between different languages or programs. It is similar to json, but json is simpler to use. The exchange method before json
14. PyYAML module
Python can also easily handle the ymal file format, but you need to install a module
Python module can refer to this link: https://blog.csdn.net/ichen820/article/details/115206216