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


当前回答

在Python 3.6.4中,可以持久化sys。通过python会话的路径如下所示:

import sys
import os

print(str(sys.path))

dir_path = os.path.dirname(os.path.realpath(__file__))
print(f"current working dir: {dir_path}")

root_dir = dir_path.replace("/util", '', 1)
print(f"root dir: {root_dir}")

sys.path.insert(0, root_dir)

print(str(sys.path))

我强烈建议你使用virtualenv和virtualenvwrapper,否则你会弄乱你的路径

其他回答

我在Windows Vista中永久添加了Python 3.5

系统>控制面板>系统高级设置>高级(点击)环境变量>系统变量>(如果在变量列中没有看到PYTHONPATH)(点击)新建>变量名称:PYTHONPATH >变量值:

请将目录写在变量值中。这是Blue Peppers回答的细节。

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

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

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

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

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

在.bash_profile文件的末尾。

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

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

除了操作PYTHONPATH,您还可以创建一个路径配置文件。首先找出Python在哪个目录中搜索这些信息:

python -m site --user-site

出于某种原因,这在Python 2.7中似乎不起作用。你可以使用:

python -c 'import site; site._script()' --user-site

然后在该目录中创建一个.pth文件,其中包含您想要添加的路径(如果目录不存在,则创建该目录)。

例如:

# find directory
SITEDIR=$(python -m site --user-site)

# create if it doesn't exist
mkdir -p "$SITEDIR"

# create new .pth file with our path
echo "$HOME/foo/bar" > "$SITEDIR/somelib.pth"