Suppose python_test
there are two folders in the project directory p1
andp2
|____p2
| |____a.py
| |______init__.py
|____p1
| |______init__.py
| |____x.py
# p1/x.py
def show():
print('this is module x')
# p2/a.py
import p1.x as haha
def show():
print('this is module a')
if __name__ == "__main__":
haha.show()
As you want a.py
the code to run smoothly, we need to let the python parser automatically search path searched p1
atx.py
python automatic search path like this:
- The root directory of the program (if you run
a.py
the file, the root directorypython_test/p1
) - Directory PYTHONPATH environment variable settings
- The standard library directory
- .Pth able to find any content files available
site.getsitepackages()
to view. - Third-party expansion site_package directory
While there are ways to introduce online search path in the program, such as: sys.path.append()
, but they need to use relative paths jumping and unscientific.
Therefore, in the case of third-party libraries for python to do this project, PYTHONPATH recommended way to import it into the project directory python environment variable. Windows Add method to set the environment variable in the advanced system environment variable.
linux, mac under the directory to the user ~/.bashrc
or other configuration files, such as .bash_profile
or.zshrc
export PYTHONPATH="/Users/cpr/Desktop/project/python_test"
export PYTHONPATH=$PYTHONPATH:"/Users/cpr/Desktop/project/testxxx"
Note that when you first add PYTHONPATH do not recommend $PYTHONPATH:
additional way, otherwise it will be more of a path environment variable home directory.
After the addition the configuration, the terminal restart, orsource ~/.bashrc
Anyway, after the configuration, you need the python sys.path
see a corresponding change
>>> import sys
>>> sys.path
['', '/Users/cpr/Desktop/project/python_test', '/Users/cpr/Desktop/project/test', '/usr/local/Cellar/python/3.7.4/Frameworks/Python.framework/Versions/3.7/lib/python37.zip', '/usr/local/Cellar/python/3.7.4/Frameworks/Python.framework/Versions/3.7/lib/python3.7', '/usr/local/Cellar/python/3.7.4/Frameworks/Python.framework/Versions/3.7/lib/python3.7/lib-dynload', '/Users/cpr/Library/Python/3.7/lib/python/site-packages', '/usr/local/lib/python3.7/site-packages', '/usr/local/Cellar/protobuf/3.9.2/libexec/lib/python3.7/site-packages']
Then go execute a.py
to successfully call a function in another package.