每当我使用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))

其他回答

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

A <-> B之间的最短路径是一条直线;

import sys
if not 'NEW_PATH' in sys.path:
  sys.path += ['NEW_PATH']

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

~/.bash_profile 

让我很开心,例如:

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

这样做之后:

source ~/.bash_profile

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

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

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

在.bash_profile文件的末尾。

我找到了一个解决方案,在水蟒环境中做到这一点:https://datacomy.com/python/anaconda/add_folder_to_path/

只是:

Conda develop /your_path