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


当前回答

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

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

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

其他回答

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

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

受到andrei-deusteanu答案的启发,以下是我的版本。这允许您在site-packages目录中创建许多额外的路径。

import os

# Add paths here.  Then Run this block of code once and restart kernel. Paths should now be set.
paths_of_directories_to_add = [r'C:\GIT\project1', r'C:\GIT\project2', r'C:\GIT\project3']

# Find your site-packages directory
pathSitePckgs = os.path.join(os.path.dirname(os.__file__), 'site-packages')

# Write a .pth file in your site-packages directory
pthFile = os.path.join(pathSitePckgs,'current_machine_paths.pth')
with open(pthFile,'w') as pth_file:
    pth_file.write('\n'.join(paths_of_directories_to_add))

print(pthFile)

如果有人仍然感到困惑,如果你在Mac上,请执行以下操作:

打开终端 输入open .bash_profile 在弹出的文本文件中,在最后添加这行: 出口到PYTHONPATH = $ PYTHONPATH: foo / bar 保存文件,重新启动终端,就完成了

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

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

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

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

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

我不得不取消注释一行:

看一看

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

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

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