每当我使用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,否则你会弄乱你的路径

其他回答

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

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

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

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

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

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

在MacOS上,而不是给出特定库的路径。给出根项目文件夹的完整路径

~/.bash_profile 

让我很开心,例如:

export PYTHONPATH="${PYTHONPATH}:/Users/<myuser>/project_root_folder_path"

这样做之后:

source ~/.bash_profile