每当我使用sys.path。追加,新目录将被添加。然而,一旦我关闭python,列表将恢复到以前的(默认?)值。如何将目录永久添加到PYTHONPATH?
当前回答
我在Windows Vista中永久添加了Python 3.5
系统>控制面板>系统高级设置>高级(点击)环境变量>系统变量>(如果在变量列中没有看到PYTHONPATH)(点击)新建>变量名称:PYTHONPATH >变量值:
请将目录写在变量值中。这是Blue Peppers回答的细节。
其他回答
如果您正在使用bash(在Mac或GNU/Linux发行版上),请将此添加到~/.bashrc中
export PYTHONPATH="${PYTHONPATH}:/my/other/path"
您可以通过pythonrc文件添加路径,该文件默认为~/。linux上的Pythonrc。ie。
import sys
sys.path.append('/path/to/dir')
您还可以在全局rc文件中设置PYTHONPATH环境变量,例如~/。mac或linux上的配置文件,或通过控制面板->系统->高级选项卡-> windows上的环境变量。
在MacOS上,而不是给出特定库的路径。给出根项目文件夹的完整路径
~/.bash_profile
让我很开心,例如:
export PYTHONPATH="${PYTHONPATH}:/Users/<myuser>/project_root_folder_path"
这样做之后:
source ~/.bash_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)
下面的脚本可以在所有平台上运行,因为它是纯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))
推荐文章
- 如何从scikit-learn决策树中提取决策规则?
- 为什么在Mac OS X v10.9 (Mavericks)的终端中apt-get功能不起作用?
- 将旋转的xtick标签与各自的xtick对齐
- 为什么元组可以包含可变项?
- 如何合并字典的字典?
- 如何创建类属性?
- 不区分大小写的“in”
- 在Python中获取迭代器中的元素个数
- 解析日期字符串并更改格式
- 我如何找到哪个程序正在使用端口80在Windows?
- 使用try和。Python中的if
- 在Windows中有像GREP这样的模式匹配实用程序吗?
- 如何在Python中获得所有直接子目录
- 我如何告诉matplotlib我已经完成了一个情节?
- 如何在Python中记录源文件名称和行号