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


当前回答

将export PYTHONPATH="${PYTHONPATH}:/my/other/path"添加到~/。如果PYTHONPATH当前不存在(因为:),bashrc可能无法工作。

export PYTHONPATH="/my/other/path1"
export PYTHONPATH="${PYTHONPATH}:/my/other/path2"

将以上内容添加到我的~/。bashrc在Ubuntu 16.04上为我完成了这个任务

其他回答

受到andrei-deusteanu答案的启发,以下是我的版本。这允许您在site-packages目录中创建许多额外的路径。

import os

# Add paths here.  Then Run this block of code once and restart kernel. Paths should now be set.
paths_of_directories_to_add = [r'C:\GIT\project1', r'C:\GIT\project2', r'C:\GIT\project3']

# Find your site-packages directory
pathSitePckgs = os.path.join(os.path.dirname(os.__file__), 'site-packages')

# Write a .pth file in your site-packages directory
pthFile = os.path.join(pathSitePckgs,'current_machine_paths.pth')
with open(pthFile,'w') as pth_file:
    pth_file.write('\n'.join(paths_of_directories_to_add))

print(pthFile)

向PYTHONPATH添加新路径是手动执行的:

将路径添加到~/。Bashrc剖面,在终端由:

vim ~/.bashrc

将以下内容粘贴到您的配置文件中

export PYTHONPATH="${PYTHONPATH}:/User/johndoe/pythonModule"

然后,当你在终端中运行你的代码时,确保你的bashrc配置文件的来源:

source ~/.bashrc 

希望这能有所帮助。

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

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

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

在.bash_profile文件的末尾。

在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,否则你会弄乱你的路径

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

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