Python exercises-modules and packages

Exercise 1: First experience of module settings
1. __doc __ print out the functional description of the module or its function

Designed module: named mymodule01

"""
本模块用于计算公司员工的薪资
"""

company = "Clichong"

def yearsalary(monthsalary):
    """根据传入的月薪,计算出年薪"""
    return monthsalary*12

def daysalary(monthsalary):
    """根据出入的月薪,计算出日薪"""
    return monthsalary/12

Test code:

import mymodule01
import math

#测试自定义的模块
print(mymodule01.__doc__)
print(mymodule01.yearsalary.__doc__)
print(mymodule01.daysalary.__doc__)

#测试第三方库模块
print(math.cos.__doc__)
print(math.acos.__doc__)

result:
Insert picture description here

2. __name __ can get the name of the module
"""
本模块用于计算公司员工的薪资
"""

company = "Clichong"

def yearsalary(monthsalary):
    """根据传入的月薪,计算出年薪"""
    return monthsalary*12

def daysalary(monthsalary):
    """根据出入的月薪,计算出日薪"""
    return monthsalary/12

print(yearsalary.__name__)
print(__name__)

#可以自定义测试函数
if __name__ == "__main__":
    print(yearsalary(10000))
    print(daysalary(10000))

Insert picture description here
Also call the module:

import mymodule01
import math

print(math.__name__)
print(mymodule01.__name__)
print(mymodule01.daysalary.__name__)

When the module is called again, all the code will be executed, including two print statements. And the name of __name __ in the test file is not __main__, but becomes the name of the module mymodule01
Insert picture description here

3. Import problem and importlib module

The basic syntax format of the import statement is as follows:
import module name#import a module
import module 1, module 2...
#import multiple modules import module name as module alias#import the module and use the new name
from module name import member 1, member 2, …

#自定义导入模块名
from mymodule01 import daysalary as dd
from math import cos

#动态导入测试
import importlib

print(cos.__name__)
print(my.__name__)
print(dd.__name__)

s = "math"
Clichong = importlib.import_module(s)
print(Clichong.pi)

Insert picture description here
Generally speaking, a module can only be imported once and cannot be imported multiple times. Sometimes we do need to reload a module. At this time, we can use: importlib.reload()

Exercise 2: Use of package
1. Import of packages
  1. When import a.aa.module_AA
    is used, it must be quoted with a full name, for example: a.aa.module_AA.fun_AA()

  2. When using from a.aa import module_AA , you can directly use the module name. For example: module_AA.fun_AA()
  3. from a.aa.module_AA import fun_AA Import function directly
    When using, you can directly use the function name. For example: fun_AA()

ps:
1) In this grammar from package import item, item can be a package, a module, or a function,
class, or variable.
2) In the grammar of import item1.item2, item must be a package or module, not others.

The essence of the imported package is actually the "__init__.py imported package" file. In other words, "import pack1" means that the __init__.py file under pack1 is executed. In this way, we can import the modules we need in batches in __init__.py, instead of importing them one by one.
The three core functions of __init__.py:

  1. As the identifier of the package, it cannot be deleted.
  2. Used to implement fuzzy import
  3. The essence of importing a package is to execute the __init__.py file, which can be initialized in the __init__.py file, and the
    code needs to be uniformly executed and batch imported.
2. Inclusive citation

from… import module_A #…represents the upper level directory. represents the same level directory
from. import module_A2 #.represents the same level directory
Insert picture description here

Exercise 3: sys module search path

When we import a certain module file, where does the Python interpreter look for this file? Only when this file is found can the module file be read, loaded and run. It generally searches for the module file according to the following path (search in order, stop and continue searching when found):

  1. Built-in module
  2. Current directory
  3. The main directory of the program
  4. pythonpath directory (if pythonpath environment variable has been set) #permanently valid
  5. Standard link library directory
  6. Third-party library directory (site-packages directory)
  7. The content of the .pth file (if it exists) #Permanently valid
  8. sys.path.append() temporarily added directory# is only valid for the current program

View the current search path:

import sys
#sys.path.append( "d:/")	#动态添加环境变量
print(sys.path)

The results are as follows:

['E:\\PyCharm\\workspace\\myImport', 'E:\\PyCharm\\workspace\\myImport', 'E:\\PyCharm\\PyCharm 2019.3.3\\plugins\\python\\helpers\\pycharm_display', 'E:\\PyCharm\\workspace\\myImport\\venv\\Scripts\\python37.zip', 'E:\\python\\python3.7\\DLLs', 'E:\\python\\python3.7\\lib', 'E:\\python\\python3.7', 'E:\\PyCharm\\workspace\\myImport\\venv', 'E:\\PyCharm\\workspace\\myImport\\venv\\lib\\site-packages', 'E:\\PyCharm\\workspace\\myImport\\venv\\lib\\site-packages\\setuptools-40.8.0-py3.7.egg', 'E:\\PyCharm\\workspace\\myImport\\venv\\lib\\site-packages\\pip-19.0.3-py3.7.egg', 'E:\\PyCharm\\PyCharm 2019.3.3\\plugins\\python\\helpers\\pycharm_matplotlib_backend']
1. The setting of pythonpath environment variable

Insert picture description here
Insert picture description here
Insert picture description here
Insert picture description here
You can see that it has been built

2.·.pth file environment variable settings

Add a .pth file under E:\python\python3.7\Lib\site-packages directory. And add content to the file.
Insert picture description here

Exercise 4: Local release and installation of the module
1. Local release of the module
  1. Create a folder with the following structure for the module file (generally, the name of the folder is the same as the name of the module)
    Insert picture description here
  2. Create a file named "setup.py" in the folder with the following content:
from distutils.core import setup
setup(
name='mypackage', # 对外我们模块的名字
version='1.1.1', # 版本号
description='这是第一个描述,用于测试本地包的发布', #描述
author='Clichong', # 作者
author_email='[email protected]',
py_modules=['mypackage.module01','mypackage.module02'] # 要发布的模块,还有一个不发布
)
  1. Build a release file. Through the terminal, cd to the module folder c, and then type the command: The
    Insert picture description here
    command is:
python setup.py sdist

Insert picture description here
After execution, the directory structure becomes:
Insert picture description here
Insert picture description here

2. Module local installation
  1. Install the release on your local computer. Still operating in cmd command line mode, enter the directory where setup.py is located, and type the command
python setup.py install

Insert picture description here
2. After the installation is successful, we enter the python directory/Lib/site-packages directory (the third-party modules are installed here, and the path will be searched when the python interpreter is executed).
Insert picture description here
Use test:
Insert picture description here
Insert picture description here
success!

Exercise 5: Upload the module to PyPI

Reference link: official document

  1. Register on the PyPI website: http://pypi.python.org
  2. Create a user information file .pypirc
    Create a file named .pypirc in the user's home directory with the content:
[distutils]
index-servers=pypi
[pypi]
repository = https://upload.pypi.org/legacy/
username = 账户名
password = 你自己的密码

[Note]
The home directory of Linux: ~/.pypirc
The home directory of Windows is: c:/user/username
. It will fail to create a file that does not contain a file name directly under windows, so the file name is ".pypirc." ,
There are two points before and after.

  1. Upload and publish remotely.
    Enter the directory where the setup.py file is located, and use the command "python setup.py sdist upload" to upload and publish the module code
  2. If your module has been uploaded successfully, then when you log in to the PyPI website, you should be able to see the management entry in the navigation bar on the right. After you click the package name to enter, you can manage your module. Of course, you can also delete this module from here.

Guess you like

Origin blog.csdn.net/weixin_44751294/article/details/109775049