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


当前回答

您可以通过pythonrc文件添加路径,该文件默认为~/。linux上的Pythonrc。ie。

import sys
sys.path.append('/path/to/dir')

您还可以在全局rc文件中设置PYTHONPATH环境变量,例如~/。mac或linux上的配置文件,或通过控制面板->系统->高级选项卡-> windows上的环境变量。

其他回答

为了给出更多的解释,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文件管理(这似乎过于复杂)的人来说,在我的Windows 11笔记本电脑上创建.pth文件工作得非常完美(我在Windows中使用Visual Studio Code)。所以只要找到你的虚拟环境站点包的文件夹——这是我的:

创建一个扩展名为.pth的文本文件——我把我的文件命名为wheal.pth:

为它添加路径:

在VS Code中最好的事情是导入语句可以识别这个路径(我不得不退出VS Code并返回),所以现在更多的输入# type: ignore来抑制linting警告消息!

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

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

这是对这个线程的更新,它有一些旧的答案。

对于那些使用MAC-OS Catalina或更新版本(>= 10.15)的用户,它引入了一个名为zsh的新终端(旧bash的替代品)。

由于这个更改,我在上面的回答中遇到了一些问题,我通过创建文件~/来解决一些问题。并将文件目录粘贴到$PATH和$PYTHONPATH

所以,首先我做了:

nano ~/.zshrc

当编辑器打开时,我粘贴以下内容:

export PATH="${PATH}:/Users/caio.hc.oliveira/Library/Python/3.7/bin"
export PYTHONPATH="${PYTHONPATH}:/Users/caio.hc.oliveira/Library/Python/3.7/bin"

保存,并重新启动终端。

重要提示:上面的路径设置为我的计算机的路径,你必须适应你的python。

对我来说,当我更改.bash_profile文件时,它起作用了。只是改变.bashrc文件工作,直到我重新启动shell。

对于python 2.7,它应该是这样的:

export PYTHONPATH="$PYTHONPATH:/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python"

在.bash_profile文件的末尾。