每当我使用sys.path。追加,新目录将被添加。然而,一旦我关闭python,列表将恢复到以前的(默认?)值。如何将目录永久添加到PYTHONPATH?
当前回答
我在Windows Vista中永久添加了Python 3.5
系统>控制面板>系统高级设置>高级(点击)环境变量>系统变量>(如果在变量列中没有看到PYTHONPATH)(点击)新建>变量名称:PYTHONPATH >变量值:
请将目录写在变量值中。这是Blue Peppers回答的细节。
其他回答
如果有人仍然感到困惑,如果你在Mac上,请执行以下操作:
打开终端 输入open .bash_profile 在弹出的文本文件中,在最后添加这行: 出口到PYTHONPATH = $ PYTHONPATH: foo / bar 保存文件,重新启动终端,就完成了
在linux上,您可以创建从包到PYTHONPATH目录的符号链接,而不必处理环境变量。喜欢的东西:
ln -s /your/path /usr/lib/pymodules/python2.7/
A <-> B之间的最短路径是一条直线;
import sys
if not 'NEW_PATH' in sys.path:
sys.path += ['NEW_PATH']
受到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)
对我来说,当我更改.bash_profile文件时,它起作用了。只是改变.bashrc文件工作,直到我重新启动shell。
对于python 2.7,它应该是这样的:
export PYTHONPATH="$PYTHONPATH:/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python"
在.bash_profile文件的末尾。