这是我所学到的:PYTHONPATH是一个目录,可添加到Python导入搜索路径“sys.path”中,该路径由当前目录CWD、PYTHONPATH、标准和共享库以及客户端库组成。例如:
% python3 -c "import sys;print(sys.path)"
['',
'/home/username/Documents/DjangoTutorial/mySite',
'/usr/lib/python3.6', '/usr/lib/python3.6/lib-dynload',
'/usr/local/lib/python3.6/dist-packages', '/usr/lib/python3/dist-packages']
第一个路径“”表示当前目录,第二个路径通过
。
%export PYTHONPATH=/home/username/Documents/DjangoTutorial/mySite
可以添加到~/.bashrc使其永久化,其余部分是Python标准和动态共享库(dynamic shared library)以及第三方库如django。
如上所述,请勿混淆PYTHONHOME,即使将其设置为''或'None'也会导致python3 shell停止工作:
% export PYTHONHOME=''
% python3
Fatal Python error: Py_Initialize: Unable to get the locale encoding
ModuleNotFoundError: No module named 'encodings'
Current thread 0x00007f18a44ff740 (most recent call first):
Aborted (core dumped)
请注意,如果您启动一个Python脚本,当前工作目录将是脚本所在的目录。例如:
username@bud:~/Documents/DjangoTutorial% python3 mySite/manage.py runserver
==== Printing sys.path ====
/home/username/Documents/DjangoTutorial/mySite # CWD is where manage.py resides
/usr/lib/python3.6
/usr/lib/python3.6/lib-dynload
/usr/local/lib/python3.6/dist-packages
/usr/lib/python3/dist-packages
您可以在运行时将路径附加到sys.path:
假设您的文件Fibonacci.py在~/Documents/Python目录中:
username@bud:~/Documents/DjangoTutorial% python3
>>> sys.path.append("/home/username/Documents")
>>> print(sys.path)
['', '/usr/lib/python3.6', '/usr/lib/python3.6/lib-dynload',
'/usr/local/lib/python3.6/dist-packages', '/usr/lib/python3/dist-packages',
'/home/username/Documents']
>>> from Python import Fibonacci as fibo
或通过
% PYTHONPATH=/home/username/Documents:$PYTHONPATH
% python3
>>> print(sys.path)
['',
'/home/username/Documents', '/home/username/Documents/DjangoTutorial/mySite',
'/usr/lib/python3.6', '/usr/lib/python3.6/lib-dynload',
'/usr/local/lib/python3.6/dist-packages', '/usr/lib/python3/dist-packages']
>>> from Python import Fibonacci as fibo