当前位置:网站首页>Day14 function module
Day14 function module
2022-07-23 15:58:00 【Bruce_ Liuxiaowei】
day14 modular

master Python How to use common modules in .
- Custom module ( package )
- Third-party module
- Built-in module 【1/2】
1. Custom module
1.1 Modules and packages
import hashlib
def encrypt(data):
""" Data encryption """
hash_object = hashlib.md5()
hash_object.update(data.encode('utf-8'))
return hash_object.hexdigest()
user = input(" Please enter a user name :")
pwd = input(" Please input a password :")
md5_password = encrypt(pwd)
message = " user name :{}, password :{}".format(user, md5_password)
print(message)
When developing simple programs , Use one py The file can be done , If the program is relatively large , Need some 10w Line code , At this time, in order to , The code structure is clear , Split functions into different ones according to certain rules py In file , When you use it, you can import it . in addition , When other projects also need some modules of this project , You can also take the module directly to use , Increase reusability .
If you split according to a certain rule , Found split to commons.py Too many functions in , You can also split again through folders , for example :
├── commons
│ ├── convert.py
│ ├── page.py
│ └── utils.py
└── run.py
stay Python The general title of documents and documents in ( Many developers are also called modules in their daily development )
- One py file , modular (module).
- Multiple py File folder , package (package).
Be careful : In the bag ( Folder ) One of the default contents is empty __init__.py The file of , Generally used to describe the information of the current package ( When importing the following modules , It will also load automatically ).
- py2 There has to be , If the package is not imported, it will fail .
- py3 not essential .
1.2 Import
After defining a module or package , If you want to use the functions defined therein , You must first import , Then you can use .
Import , In fact, it is to load modules or packages into memory , Go to the memory to get it later .
About the path of derivation as time :
stay Python Some paths are set internally by default , When importing a module or package , Will find specific paths one by one in the specified order .
import sys
print(sys.path)
[
' Directory of currently executing script ',
'/Users/liuxiaowei/PycharmProjects/ Lu Feiquan stack /day14', '/Users/liuxiaowei/PycharmProjects/ Lu Feiquan stack ', '/Applications/PyCharm.app/Contents/plugins/python/helpers/pycharm_display', '/Library/Frameworks/Python.framework/Versions/3.9/lib/python39.zip', '/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9', '/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/lib-dynload', '/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages', '/Applications/PyCharm.app/Contents/plugins/python/helpers/pycharm_matplotlib_backend'
]
Want to import arbitrary modules and packages , Must be written in the following path , To be found .
It can also be automatically and manually in sys.path Add the specified path to the , Then you can import , for example :
import sys
sys.path.append(" route A")
import xxxxx # Import path A Under a xxxxx.py file
1. When you write the module name later , Never have the same name as built-in and third-party ( Novices are prone to make mistakes ).
2. Project execution files are usually in the root directory of the project , If the execution file is nested in the memory directory , You need to manually sys.path Add path to .
3.pycharm By default, the project directory will be added to sys.path in
- pycharm By default, the project directory will be added to sys.path in
About how to import :
Import essentially loads the contents of a file into memory first , Then go to the memory and get it for use . And in the Python Common import methods in development include 2 Class mode , There are many situations in each way .
The first category :import xxxx( In development , It is usually used for importing sys.path A... In the catalog py file )
Module level
├── commons │ ├── __init__.py │ ├── convert.py │ ├── page.py │ ├── tencent │ │ ├── __init__.py │ │ ├── sms.py │ │ └── wechat.py │ └── utils.py ├── many.py └── run.pyPackage level
├── commons │ ├── __init__.py │ ├── convert.py │ ├── page.py │ └── utils.py ├── third │ ├── __init__.py │ ├── ali │ │ └── oss.py │ └── tencent │ ├── __init__.py │ ├── __pycache__ │ ├── sms.py │ └── wechat.py └── run.p
The second category :from xxx import xxx 【 Commonly used 】, It is generally applicable to multi-level nesting and importing a member of a module .
Member level
├── commons │ ├── __init__.py │ ├── convert.py │ ├── page.py │ └── utils.py ├── many.py └── run.pyTips : be based on from Patterns can also support
from many import *, namely : Import all members in a module ( May have duplicate names , So use less ).Module level
├── commons │ ├── __init__.py │ ├── convert.py │ ├── page.py │ └── utils.py ├── many.py └── run.pyPackage level
├── commons │ ├── __init__.py │ ├── convert.py │ ├── page.py │ ├── tencent │ │ ├── __init__.py │ │ ├── sms.py │ │ └── wechat.py │ └── utils.py ├── many.py └── run.py
1.3 Relative Import
When importing the module , about
from xx import xxThis model , It also supports relative Import . for example :

Bear in mind , Relative import can only be used in py In file ( namely : Nested in a file py Documents can only be used , The project root directory cannot be used ).

1.4 Import alias
If you import member / modular / package Have duplicate names , Then the later import will overwrite the previous import , To avoid this happening ,Python Support rename , namely :
from xxx.xxx import xx as xo
import x1.x2 as pg
besides , With as The existence of , Give Way import xx.xxx.xxxx.xxx When calling execution , It's going to be easier ( Not commonly used , Understanding can ).
- original
import commons.page
v1 = commons.page.pagination()
- Now?
import commons.page as pg
v1 = pg.pagination()
1.5 Master file
Execute one py When you file
__name__ = "__main__"Import a py When you file
__name__ = " Module name "
Master file , In fact, it is the entry file in the program execution , for example :
├── commons
│ ├── __init__.py
│ ├── convert.py
│ ├── page.py
│ ├── tencent
│ │ ├── __init__.py
│ │ ├── sms.py
│ │ └── wechat.py
│ └── utils.py
├── many.py
└── run.py
We usually execute run.py To run the program , Other py Files are all function codes . When we execute a file , Inside the document __name__ The value of the variable is __main__, therefore , The master file is often seen :
import many
from commons import page
from commons import utils
def start():
v1 = many.show()
v2 = page.pagination()
v3 = utils.encrypt()
if __name__ == '__main__':
start()
Only when you run this script as a master file start Function to execute , When imported, it will not be executed .
Summary
The difference between modules and packages
Two ways to import modules :
import xx from xxx import xxxRelative Import , Package name is required .
Module duplicate names can be obtained by as Take the alias .
perform py When you file , Inside
__name__=="__main__", When importing a module , Imported modules__name__=" Module name "In project development , Generally, it will be written in the main file main ( Main file mark , Not absolutely , Because other files may sometimes exist during development and debugging main).
MAC System , namely :Python Of the installation path bin Under the table of contents
2. Third-party module
Python The modules provided internally are limited , So in the process of development , Third party modules are often used .
Third party modules must be installed before they can be used , Here are some common 3 How to install third-party modules in .
Actually , The behavior of using third-party modules is to use others to write and open source py Code , So you can use it yourself , There is no need to build wheels again ....
2.1 pip( The most commonly used )
This is a Python The most commonly used way to install third-party modules .
pip It is actually a third-party module package management tool , Default installation Python The interpreter will be installed automatically , default directory :
MAC System , namely :Python Of the installation path bin Under the table of contents
/Library/Frameworks/Python.framework/Versions/3.9/bin/pip3
/Library/Frameworks/Python.framework/Versions/3.9/bin/pip3.9
Windows System , namely :Python Of the installation path scripts Under the table of contents
C:\Python39\Scripts\pip3.exe
C:\Python39\Scripts\pip3.9.exe
Tips : For the convenience of running at the terminal pip Management tools , We will also add its path to the system environment variable .
pip3 install Module name
If something written on your computer is not found pip, You can also install it manually :
download
get-pip.pyfile , To any directoryAddress :https://bootstrap.pypa.io/get-pip.pyOpen the terminal and enter the directory , use Python The interpreter runs the downloaded
get-pip.pyThe file was installed immediately .
Use pip It is also very easy to install third-party modules , You only need to execute on your own terminal :pip install Module name that will do

The latest version is installed by default , If you want to specify the version :
pip3 install Module name == edition
for example :
pip3 install django==2.2
2.1.1 pip to update
The yellow font above suggests : Currently on my computer pip yes 20.2.3 edition , The latest is 20.3.3 edition , If you want to upgrade to the latest version , You can execute the command prompted by him at the terminal :
/Library/Frameworks/Python.framework/Versions/3.9/bin/python3.9 -m pip install --upgrade pip
Be careful : Execute according to the prompt command of your computer , Don't use my prompt command here .
2.1.2 Douban source
pip The default is to https://pypi.org Go to download the third-party module ( In essence, it is written by others py Code ), The speed of foreign websites will be relatively slow , In order to speed up the use of domestic sources of watercress .
One time use
pip3.9 install Module name -i https://pypi.douban.com/simple/Permanent use
To configure
# Execute the following command at the terminal pip3.9 config set global.index-url https://pypi.douban.com/simple/ # After execution , Prompt: the Douban source is written in my local file , We'll go through it later pip When installing third-party modules , The Douban source will be used by default . # You can also open the file and modify the source address directly in the future . Writing to /Users/wupeiqi/.config/pip/pip.confUse
pip3.9 install Module name
At the end , There are other sources to choose from ( Douban is widely used ).
Alibaba cloud :http://mirrors.aliyun.com/pypi/simple/
University of science and technology of China :https://pypi.mirrors.ustc.edu.cn/simple/
Tsinghua University :https://pypi.tuna.tsinghua.edu.cn/simple/
University of science and technology of China :http://pypi.mirrors.ustc.edu.cn/simple/
2.2 Source code
If the module to be installed is pypi.org Does not exist in the or Unable to pass due to special reasons pip install When installing , You can download the source code directly , Then install based on the source code , for example :
download requests Source code ( Compressed package zip、tar、tar.gz) And extract the .
Download address :https://pypi.org/project/requests/#filesEntry directory
Execute compile and install commands
python3 setup.py build python3 setup.py install
2.3 wheel
wheel yes Python A file format of the third-party module package , We can also be based on wheel Install some third-party modules .
install wheel Format support , such pip When installing the third-party module , You can deal with wheel The format of the file .
pip3.9 install wheelDownload third-party packages (wheel Format ), for example :https://pypi.org/project/requests/#files

Enter download directory , Based on pip Direct installation

No matter how you install the third-party module , The default module installation path is :
Max System :
/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages
Windows System :
C:\Python39\Lib\site-packages\
remind : This catalog is in sys.path in , So we can import the downloaded third-party packages directly into the code .
3. Built-in module ( One )
Python There are many built-in modules , We have also contacted many related modules , Next, let's do some summary and introduction .
There are many built-in modules & There are also many functions in the module , We can't pay attention to the overall situation and explain it to you , Here I will sort out the most commonly used ones for project development to explain .
3.1 os
import os
# 1. Get the absolute path of the current script
""" abs_path = os.path.abspath(__file__) print(abs_path) """
# 2. Get the parent directory of the current file
""" base_path = os.path.dirname( os.path.dirname( route ) ) print(base_path) """
# 3. Path splicing
""" p1 = os.path.join(base_path, 'xx') print(p1) p2 = os.path.join(base_path, 'xx', 'oo', 'a1.png') print(p2) """
# 4. Determine if the path exists
""" exists = os.path.exists(p1) print(exists) """
# 5. Create folder
""" os.makedirs( route ) """
""" path = os.path.join(base_path, 'xx', 'oo', 'uuuu') if not os.path.exists(path): os.makedirs(path) """
# 6. Is it a folder
""" file_path = os.path.join(base_path, 'xx', 'oo', 'uuuu.png') is_dir = os.path.isdir(file_path) print(is_dir) # False folder_path = os.path.join(base_path, 'xx', 'oo', 'uuuu') is_dir = os.path.isdir(folder_path) print(is_dir) # True """
# 7. Delete files or folders
""" os.remove(" File path ") """
""" path = os.path.join(base_path, 'xx') shutil.rmtree(path) """
- listdir, View all files in the directory
- walk, View all files in the directory ( Documents including descendants
import os
""" data = os.listdir("/Users/wupeiqi/PycharmProjects/luffyCourse/day14/commons") print(data) # ['convert.py', '__init__.py', 'page.py', '__pycache__', 'utils.py', 'tencent'] """
""" To traverse all the files in a folder , for example : Traverse all the folders mp4 file """
data = os.walk("/Users/wupeiqi/Documents/ Video tutorial / Monkey D Luffy Python/mp4")
for path, folder_list, file_list in data:
for file_name in file_list:
file_abs_path = os.path.join(path, file_name)
ext = file_abs_path.rsplit(".",1)[-1]
if ext == "mp4":
print(file_abs_path)
3.2 shutil
import shutil
# 1. Delete folder
""" path = os.path.join(base_path, 'xx') shutil.rmtree(path) """
# 2. Copy folder
""" shutil.copytree("/Users/wupeiqi/Desktop/ chart /csdn/","/Users/wupeiqi/PycharmProjects/CodeRepository/files") """
# 3. Copy files
""" shutil.copy("/Users/wupeiqi/Desktop/ chart /csdn/[email protected]","/Users/wupeiqi/PycharmProjects/CodeRepository/") shutil.copy("/Users/wupeiqi/Desktop/ chart /csdn/[email protected]","/Users/wupeiqi/PycharmProjects/CodeRepository/x.png") """
# 4. File or folder rename
""" shutil.move("/Users/wupeiqi/PycharmProjects/CodeRepository/x.png","/Users/wupeiqi/PycharmProjects/CodeRepository/xxxx.png") shutil.move("/Users/wupeiqi/PycharmProjects/CodeRepository/files","/Users/wupeiqi/PycharmProjects/CodeRepository/images") """
# 5. Compressed files
""" # base_name, Compressed package file # format, Compressed format , for example :"zip", "tar", "gztar", "bztar", or "xztar". # root_dir, Folder path to compress """
# shutil.make_archive(base_name=r'datafile',format='zip',root_dir=r'files')
# 6. Unzip the file
""" # filename, Zip file to unzip # extract_dir, Decompression path # format, Compressed file format """
# shutil.unpack_archive(filename=r'datafile.zip', extract_dir=r'xxxxxx/xo', format='zip')
3.3 sys
import sys
# 1. Get the interpreter version
""" print(sys.version) print(sys.version_info) print(sys.version_info.major, sys.version_info.minor, sys.version_info.micro) """
# 2. Import module path
""" print(sys.path) """
- argv, When executing a script ,python Parameters passed in after the interpreter
import sys
print(sys.argv)
# [
# '/Users/wupeiqi/PycharmProjects/luffyCourse/day14/2. Accept the parameters for executing the script .py'
# ]
# [
# "2. Accept the parameters for executing the script .py"
# ]
# ['2. Accept the parameters for executing the script .py', '127', '999', '666', 'wupeiqi']
# for example , Please implement a tool for downloading pictures .
def download_image(url):
print(" Download the pictures ", url)
def run():
# Accept the parameters passed in by the user
url_list = sys.argv[1:]
for url in url_list:
download_image(url)
if __name__ == '__main__':
run()
3.4 random
import random
# 1. Get random integers in the range
v = random.randint(10, 20)
print(v)
# 2. Get random decimals in the range
v = random.uniform(1, 10)
print(v)
# 3. Randomly extract an element
v = random.choice([11, 22, 33, 44, 55])
print(v)
# 4. Randomly extract multiple elements
v = random.sample([11, 22, 33, 44, 55], 3)
print(v)
# 5. Out of order
data = [1, 2, 3, 4, 5, 6, 7, 8, 9]
random.shuffle(data)
print(data)
3.5 hashlib
import hashlib
hash_object = hashlib.md5()
hash_object.update(" Liu Xiaowei ".encode('utf-8'))
result = hash_object.hexdigest()
print(result)
import hashlib
hash_object = hashlib.md5("iajfsdunjaksdjfasdfasdf".encode('utf-8'))
hash_object.update(" Liu Xiaowei ".encode('utf-8'))
result = hash_object.hexdigest()
print(result)
3.6 configparser
see :day09
3.7 xml
see :day09
summary
The difference between modules and packages
Learn how to import modules
- route
- Import the way
The general specifications to follow when importing modules 【 Add 】
notes : At the top of the file or init In file .
Import... At the top of the file
Import with rules , And split with blank lines .
# Built in modules first # Third party modules # Finally, customize the moduleimport os import sys import random import hashlib import requests import openpyxl from commons.utils import encrypt
Third party module installation method
Common built-in modules
边栏推荐
- Batch deletion with RPM -e --nodeps
- Without Huawei, Qualcomm will raise prices at will, and domestic mobile phones that lack core technology can only be slaughtered
- 【攻防世界WEB】难度三星9分入门题(上):simple_js、mfw
- 上课作业(5)——#576. 饥饿的牛(hunger)
- Conda设置代理
- xxl-job 实现email发送警告的代码解析(一行一行代码解读)
- 软件测试周刊(第81期):能够对抗消极的不是积极,而是专注;能够对抗焦虑的不是安慰,而是具体。
- AWS篇1
- Learning summary of ugly code
- day1
猜你喜欢
随机推荐
redis 主从复制
C语言经典例题-求最少数量钞票
C语言经典例题-将输入的两位数转成英文
(Zset)Redis底层是如何用跳表进行存储的
redis 哨兵模式
记一次SQL优化
C语言经典例题-switch case语句转换日期格式
aws篇4 一机一密
[operation and maintenance] SSH tunneling relies on the 22 port of SSH to realize the interface service of accessing the remote server
SCA在得物DevSecOps平台上应用
什么是真正的 HTAP ?(二)挑战篇
day1
PHP代码审计4—Sql注入漏洞
【论文学习】《Source Mixing and Separation Robust Audio Steganography》
PHP code audit 4 - SQL injection vulnerability
【运维】ssh tunneling 依靠ssh的22端口实现访问远程服务器的接口服务
作为测试人员,不能不懂的adb命令和操作
md5强碰撞,二次解码,
Fileinputformat of MapReduce inputformat
C language learning notes









