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


当前回答

下面的脚本可以在所有平台上运行,因为它是纯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上,请执行以下操作:

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

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

如果您正在使用bash(在Mac或GNU/Linux发行版上),请将此添加到~/.bashrc中

export PYTHONPATH="${PYTHONPATH}:/my/other/path"

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

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

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

在.bash_profile文件的末尾。

除了操作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"