每当我使用sys.path。追加,新目录将被添加。然而,一旦我关闭python,列表将恢复到以前的(默认?)值。如何将目录永久添加到PYTHONPATH?


当前回答

将export PYTHONPATH="${PYTHONPATH}:/my/other/path"添加到~/。如果PYTHONPATH当前不存在(因为:),bashrc可能无法工作。

export PYTHONPATH="/my/other/path1"
export PYTHONPATH="${PYTHONPATH}:/my/other/path2"

将以上内容添加到我的~/。bashrc在Ubuntu 16.04上为我完成了这个任务

其他回答

在linux上,您可以创建从包到PYTHONPATH目录的符号链接,而不必处理环境变量。喜欢的东西:

ln -s /your/path /usr/lib/pymodules/python2.7/

为了给出更多的解释,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.

向PYTHONPATH添加新路径是手动执行的:

将路径添加到~/。Bashrc剖面,在终端由:

vim ~/.bashrc

将以下内容粘贴到您的配置文件中

export PYTHONPATH="${PYTHONPATH}:/User/johndoe/pythonModule"

然后,当你在终端中运行你的代码时,确保你的bashrc配置文件的来源:

source ~/.bashrc 

希望这能有所帮助。

为了添加awesomo的答案,你也可以在~/中添加这一行。Bash_profile或~/.profile

修复从bash切换到zsh时Python路径问题

当我从bash切换到zsh时,我遇到了Python路径问题。

解决办法很简单,但我没有注意到。

Pip告诉我,脚本blah blah或包blah blah安装在~/。不在路径中的本地/bin。

在阅读了这个问题的一些解决方案后,我打开我的.zshrc,发现解决方案已经存在。

我不得不取消注释一行:

看一看