Calls between the engineering package python

Suppose python_testthere are two folders in the project directory p1andp2

|____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.pythe code to run smoothly, we need to let the python parser automatically search path searched p1atx.py

python automatic search path like this:

  1. The root directory of the program (if you run a.pythe file, the root directory python_test/p1)
  2. Directory PYTHONPATH environment variable settings
  3. The standard library directory
  4. .Pth able to find any content files available site.getsitepackages()to view.
  5. 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 ~/.bashrcor other configuration files, such as .bash_profileor.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.pathsee 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.pyto successfully call a function in another package.

Guess you like

Origin www.cnblogs.com/xrszff/p/11593450.html