Begin
First, direct import
Here's a major premise. The py executable file and module belong to the same directory (parent directory), such as:
01
main.py 和 pwcong模块同在python目录执行文件为main.pypwcong文件夹为一个模块
I wrote the functions provided by the Pwcong module in the init. PY, which only provides a hi function:
# pwcong 模块的 __init__.py# -*- coding: utf-8 -*-def hi(): print("hi")12345
Execute file main.py Direct Import module:
# main.py# -*- coding: utf-8 -*-import pwcongpwcong.hi()1234567
Then we run the main.py can see the command line window output a Hi, the first way to complete.
使用模块方式为:先导入-》接着输入模块.变量|函数, 如上面例子的 pwcong.hi()
Second, the path of the custom module is imported through the SYS module
If the execution file and module are not in the same directory, then the direct import cannot find the custom module. Such as:
02
执行文件main.py在main目录下pwcong模块在python目录下
SYS module is built into Python, so the steps to import a custom module are as follows:
先导入sys模块然后通过sys.path.append(path) 函数来导入自定义模块所在的目录导入自定义模块。
At this time main.py wrote:
# main.py# -*- coding: utf-8 -*-import syssys.path.append(r"C:\Users\Pwcong\Desktop\python")import pwcongpwcong.hi()12345678910
The final execution of the main.py file, the final output hi, the second way to complete.
Third, the custom module is found through the PTH file
The principle of this method is that the system variable is used, and Python scans the path of the path variable to import the module, which can be added in the system path. But I still recommend using PTH files to add.
The module and the execution file directory structure are the same:
02
执行文件main.py在main目录下pwcong模块在python目录下
We create the Crown Sports Platform Development Forum: haozbbs.com Q1446595067 A module_pwcong.pth file containing the contents of the Pwcong module:
C:\Users\Pwcong\Desktop\python
1
Place the module_pwcong.pth file here:
Python installation directory \python35\lib\site-packages
For example, my:
03
Then main.py import and use the custom module:
# -*- coding: utf-8 -*-import pwcongpwcong.hi()123456
Finally executes the main.py file, can output hi, the third way to complete.
Python3 3 ways to import custom Crown Sports Platform development modules