Generally speaking, we will store the Python modules we write and the modules that come with python separately to achieve the purpose of easy maintenance. So how to add custom modules in Python?
Before answering this question, we must first clarify two points:
Strictly distinguish between packages and folders. The definition of a package is the folder containing init.py. If there is no init.py, then it is a normal folder.
Module import writing, pay attention to only the package path, not the folder path.
The Python runtime environment traverses the sys.path list when searching for library files. If we want to register a new class library in the runtime environment, there are two main methods:
Add a new path to the sys.path list.
Copy the library file to a directory in the sys.path list (such as the site-packages directory).
We can view sys.path by running the code
import sys
print sys.path
operation result
[ ‘/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-old’, ‘/System/Library/Frameworks/Python.
framework/Versions/2.7/lib/python2.7/lib-dynload’, ‘/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/
lib/python/PyObjC’, ‘/Library/Python/2.7/site-packages’]
The first of these two methods is simpler and has the least impact on the environment.
Let's take a look at the specific operation of the first method:
Create a new pythontab.pth in the site-package folder of the python installation directory. The above site-package path is: /Library/Python/2.7/site-packages, and the content of the file is: the folder path where the package to be imported is located.
In this way, in the process of traversing the known library file directory, if Python sees a .pth file, it will add the path recorded in the file to the sys.path setting, so that the .pth file says the specified package can also After being successfully found by the Python runtime environment, we can introduce custom modules like built-in modules.
If the default sys.path does not contain the path of your own module or package, we can also use the sys.path.apend method to dynamically add the package path.
Knowledge point expansion:
Principles of adding custom modules in Python:
Strictly distinguish between packages and folders. The definition of a package is the folder containing init.py. If there is no init.py, then it is a normal folder.
Import the package. Create a new xxx.pth in the site-package folder of the python installation directory, the content is the folder path of the package to be imported.
Import the module. It is the general way of importing modules. Note that only the package path is required, not the folder path.
The above is the details of how to add custom modules in Python. For more information about adding custom modules in Python, please pay attention to other related articles on ZaLou.Cn!
Recommended Posts