If you want to do Python development, these 14 common Python modules need to know several modules!

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:
Insert picture description here
call symbol:
Insert picture description here
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:

Insert picture description here
From...import statement *

It is also possible to import all the contents of a module into the current namespace, just use the following declaration:

Insert picture description here

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

Insert picture description here

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

Insert picture description here
Import the module in the __init__.py content
Insert picture description here

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.

Insert picture description here

#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
Insert picture description here

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
Insert picture description here

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().

Insert picture description here

Time to timestamp

Insert picture description here

Formatted time string

Insert picture description here

Convert timestamp and tuple to time string

Insert picture description here

Insert picture description here

Time addition and subtraction
Insert picture description here

3. Random module
Insert picture description here

4. sys module

Insert picture description here

5. Shuil module

Advanced file, folder, copy, compressed package and other processing modules

Insert picture description here

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

Insert picture description here

What if you want to use python to generate such a document?

Generate
Insert picture description here

Read it out
Insert picture description here

Configparser add, delete, modify and check grammar
Insert picture description here

Insert picture description here

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

Insert picture description here
Insert picture description here
Insert picture description here

Python also has a hmac module, which internally processes the keys and contents that we create and then encrypts themInsert picture description here

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:

Insert picture description here

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

Insert picture description here

9, re-regular expression module

Commonly used regular expression symbols The
Insert picture description here
most common matching syntax

Insert picture description here

Group matching and group(), groups(), groupdict()
Insert picture description here

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

Insert picture description here

Take a look at what these log levels meanInsert picture description here

If you want to write the log to a file, it's also very simpleInsert picture description here

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.
Insert picture description here
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
Insert picture description here

11. JSON and pickle data serialization

str eval

Data serialization

Insert picture description here

json can only handle simple ones, common to all languages, and functions cannot be serialized by jsonInsert picture description here

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

Insert picture description here

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

Guess you like

Origin blog.csdn.net/ichen820/article/details/115206318