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

其他回答

对于那些(像我一样)不想太深入地参与Python文件管理(这似乎过于复杂)的人来说,在我的Windows 11笔记本电脑上创建.pth文件工作得非常完美(我在Windows中使用Visual Studio Code)。所以只要找到你的虚拟环境站点包的文件夹——这是我的:

创建一个扩展名为.pth的文本文件——我把我的文件命名为wheal.pth:

为它添加路径:

在VS Code中最好的事情是导入语句可以识别这个路径(我不得不退出VS Code并返回),所以现在更多的输入# type: ignore来抑制linting警告消息!

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

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

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

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

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

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

受到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)