In general, we will store our own Python modules separately from Python's own modules for easy maintenance purposes. So how do you add a custom module to Python?
Before we answer this question, we must first clarify two points:
1. Strictly differentiate between packages and folders. A package is defined as a folder that contains __init__.py. If there is no __init__.py, then it is a normal folder.
2. Import the module, note that as long as the package path, do not folder path.
The Python runtime environment, when looking for a library file, iterates over the Sys.path list, and if we want to register the new class library in the runtime environment, there are 2 main ways of doing this:
1. Add a new path in the Sys.path list.
2. Copy the library files to a directory in the Sys.path list (such as the Site-packages directory).
We can see Sys.path by running the code.
Import Sysprint 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 approaches is relatively simple and has minimal impact on the environment.
Let's take a look at the first method of how to do this:
Create a new pythontab.pth in the Site-package folder of the Python installation directory, site-package The path is:/library/python/2.7/site-packages, The content of the file is the path to the folder where the package needs to be imported.
In this way, when Python walks through a known library file directory, if a. pth file is seen, the path recorded in the file is added to the Sys.path setting so that the. pth file says that the specified package can be found in the Python run environment, We can introduce custom modules just like we do with built-in modules.
If the default Sys.path does not contain a path to its own module or package, we can also use the Sys.path.apend method to dynamically join the package path.