【问题标题】:setting python search path in config file without environment variables (i.e. PYTHONPATH)在没有环境变量的配置文件中设置 python 搜索路径(即 PYTHONPATH)
【发布时间】:2012-08-08 23:18:44
【问题描述】:

有没有办法在配置文件中设置python的搜索路径没有设置PYTHONPATH,即python启动时读取的一些默认配置文件?

【问题讨论】:

标签: python unix pythonpath


【解决方案1】:

你有两个选择:

  • .pth file in one of the standard locations(通常是您的site-packages 位置)中列出其他路径。另见How to add a Python import path using a .pth file

  • sitecustomizeusercustomize 模块中添加指向sys.path 的附加路径(在site module documentation 中有详细说明)。您的 sitecustomizeusercustomize 可能类似于:

    import sys
    sys.path[0:0] = [
        '/foo/bar',
        '/spam/eggs',
    ]
    

    两个额外的条目将被插入到前面的sys.path

    您也可以使用此类模块中的路径调用site.addsitedir,这会将路径添加到sys.path处理在那里找到的任何.pth文件。

【讨论】:

  • 所以假设我没有(或不能依赖)root 访问权限,我会将sitecustomize.py 放在site.USER_SITE 指向的路径中?
【解决方案2】:

为避免弄乱 Python 的系统安装,您可以列出您的 USER_SITE 目录中的 .pth 文件中的路径,例如 ~/.local/lib/python2.7/site-packages。你也可以把usercustomize.py放在那里,然后调用sys.path.insert(0, path)site.addsitedir(path)等任意代码。

【讨论】:

    猜你喜欢
    • 2019-03-18
    • 2020-07-29
    • 2011-08-20
    • 1970-01-01
    • 1970-01-01
    • 2014-01-21
    • 2017-06-09
    • 2018-01-04
    • 2012-10-28
    相关资源
    最近更新 更多