每当我使用sys.path。追加,新目录将被添加。然而,一旦我关闭python,列表将恢复到以前的(默认?)值。如何将目录永久添加到PYTHONPATH?
当前回答
您可以通过pythonrc文件添加路径,该文件默认为~/。linux上的Pythonrc。ie。
import sys
sys.path.append('/path/to/dir')
您还可以在全局rc文件中设置PYTHONPATH环境变量,例如~/。mac或linux上的配置文件,或通过控制面板->系统->高级选项卡-> windows上的环境变量。
其他回答
在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将使用site.py脚本(通常位于sys. py中)自动构造它的搜索路径(如上所述和这里)。Prefix + lib/python<version>/site-packages以及lib/site-python)。可以获取sys.prefix的值:
python -c 'import sys; print(sys.prefix)'
The site.py script then adds a number of directories, dependent upon the platform, such as /usr/{lib,share}/python<version>/dist-packages, /usr/local/lib/python<version>/dist-packages to the search path and also searches these paths for <package>.pth config files which contain specific additional search paths. For example easy-install maintains its collection of installed packages which are added to a system specific file e.g on Ubuntu it's /usr/local/lib/python2.7/dist-packages/easy-install.pth. On a typical system there are a bunch of these .pth files around which can explain some unexpected paths in sys.path:
python -c 'import sys; print(sys.path)'
因此,可以创建一个.pth文件,并将其放在这些目录中的任何一个目录中(包括上面提到的sitedir)。这似乎是大多数包被添加到系统的方式。而不是使用PYTHONPATH。
Note: On OSX there's a special additional search path added by site.py for 'framework builds' (but seems to work for normal command line use of python): /Library/Python/<version>/site-packages (e.g. for Python2.7: /Library/Python/2.7/site-packages/) which is where 3rd party packages are supposed to be installed (see the README in that dir). So one can add a path configuration file in there containing additional search paths e.g. create a file called /Library/Python/2.7/site-packages/pip-usr-local.pth which contains /usr/local/lib/python2.7/site-packages/ and then the system python will add that search path.
在linux上,您可以创建从包到PYTHONPATH目录的符号链接,而不必处理环境变量。喜欢的东西:
ln -s /your/path /usr/lib/pymodules/python2.7/
我找到了一个解决方案,在水蟒环境中做到这一点:https://datacomy.com/python/anaconda/add_folder_to_path/
只是:
Conda develop /your_path
将export PYTHONPATH="${PYTHONPATH}:/my/other/path"添加到~/。如果PYTHONPATH当前不存在(因为:),bashrc可能无法工作。
export PYTHONPATH="/my/other/path1"
export PYTHONPATH="${PYTHONPATH}:/my/other/path2"
将以上内容添加到我的~/。bashrc在Ubuntu 16.04上为我完成了这个任务
推荐文章
- 将Pandas或Numpy Nan替换为None以用于MysqlDB
- 使用pandas对同一列进行多个聚合
- 使用Python解析HTML
- 如何在命令提示符中使用空格?
- django MultiValueDictKeyError错误,我如何处理它
- 如何在for循环期间修改列表条目?
- 我如何在Django中创建一个鼻涕虫?
- 没有名为'django.core.urlresolvers'的模块
- 蟒蛇导出环境文件
- Django - makemigrations -未检测到任何更改
- SQLAlchemy:引擎、连接和会话差异
- 在Python Pandas中删除多个列中的所有重复行
- 更改pandas DataFrame中的特定列名
- 将Pandas多索引转换为列
- 熊猫在每组中获得最高的n个记录