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


当前回答

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

其他回答

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

~/.bash_profile 

让我很开心,例如:

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

这样做之后:

source ~/.bash_profile

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

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

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

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

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

只是:

Conda develop /your_path