每当我使用sys.path。追加,新目录将被添加。然而,一旦我关闭python,列表将恢复到以前的(默认?)值。如何将目录永久添加到PYTHONPATH?
当前回答
向PYTHONPATH添加新路径是手动执行的:
将路径添加到~/。Bashrc剖面,在终端由:
vim ~/.bashrc
将以下内容粘贴到您的配置文件中
export PYTHONPATH="${PYTHONPATH}:/User/johndoe/pythonModule"
然后,当你在终端中运行你的代码时,确保你的bashrc配置文件的来源:
source ~/.bashrc
希望这能有所帮助。
其他回答
为了给出更多的解释,Python将使用site.py脚本(通常位于sys. py中)自动构造它的搜索路径(如上所述和这里)。Prefix + lib/python<version>/site-packages以及lib/site-python)。可以获取sys.prefix的值:
python -c 'import sys; print(sys.prefix)'
The site.py script then adds a number of directories, dependent upon the platform, such as /usr/{lib,share}/python<version>/dist-packages, /usr/local/lib/python<version>/dist-packages to the search path and also searches these paths for <package>.pth config files which contain specific additional search paths. For example easy-install maintains its collection of installed packages which are added to a system specific file e.g on Ubuntu it's /usr/local/lib/python2.7/dist-packages/easy-install.pth. On a typical system there are a bunch of these .pth files around which can explain some unexpected paths in sys.path:
python -c 'import sys; print(sys.path)'
因此,可以创建一个.pth文件,并将其放在这些目录中的任何一个目录中(包括上面提到的sitedir)。这似乎是大多数包被添加到系统的方式。而不是使用PYTHONPATH。
Note: On OSX there's a special additional search path added by site.py for 'framework builds' (but seems to work for normal command line use of python): /Library/Python/<version>/site-packages (e.g. for Python2.7: /Library/Python/2.7/site-packages/) which is where 3rd party packages are supposed to be installed (see the README in that dir). So one can add a path configuration file in there containing additional search paths e.g. create a file called /Library/Python/2.7/site-packages/pip-usr-local.pth which contains /usr/local/lib/python2.7/site-packages/ and then the system python will add that search path.
下面的脚本可以在所有平台上运行,因为它是纯Python。它使用了pathlib路径(请参阅https://docs.python.org/3/library/pathlib.html),使其能够跨平台工作。运行一次,重新启动内核,就完成了。灵感来自https://medium.com/@arnaud.bertrand/ modiing-python-s - sear-path-with-pth -files-2a41a4143574。为了运行它,它需要管理员权限,因为你修改了一些系统文件。
from pathlib import Path
to_add=Path(path_of_directory_to_add)
from sys import path
if str(to_add) not in path:
minLen=999999
for index,directory in enumerate(path):
if 'site-packages' in directory and len(directory)<=minLen:
minLen=len(directory)
stpi=index
pathSitePckgs=Path(path[stpi])
with open(str(pathSitePckgs/'current_machine_paths.pth'),'w') as pth_file:
pth_file.write(str(to_add))
在Mac上:
user@terminal$ env PYTHONPATH=module_path python3
>>> import sys
>>> sys.path
['module_path', 'plus_other_python3_paths',...]
如果您正在使用bash(在Mac或GNU/Linux发行版上),请将此添加到~/.bashrc中
export PYTHONPATH="${PYTHONPATH}:/my/other/path"
这适用于Windows
在Windows上,使用Python 2.7进入Python安装文件夹。 开放的Lib /网站。 将example.pth空文件添加到此文件夹。 将所需的路径添加到文件中,每行一个。
然后,您将能够从脚本中看到这些路径中的所有模块。