什么用 Python 设置 sys.path,什么时候设置?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4271494/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
What sets up sys.path with Python, and when?
提问by prosseek
When I run
当我跑
import sys
print sys.path
on my Mac (Mac OS X 10.6.5, Python 2.6.1), I get the following results.
在我的 Mac(Mac OS X 10.6.5,Python 2.6.1)上,我得到以下结果。
/Library/Python/2.6/site-packages/ply-3.3-py2.6.egg ... /Library/Python/2.6/site-packages/ipython-0.10.1-py2.6.egg /System/Library/Frameworks/Python.framework/Versions/2.6/lib/python26.zip /System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6 /System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/plat-darwin /System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/plat-mac /System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/plat-mac/lib-scriptpackages /System/Library/Frameworks/Python.framework/Versions/2.6/Extras/lib/python /System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/lib-tk /System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/lib-old /System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/lib-dynload /Library/Python/2.6/site-packages /System/Library/Frameworks/Python.framework/Versions/2.6/Extras/lib/python/PyObjC /System/Library/Frameworks/Python.framework/Versions/2.6/Extras/lib/python/wx-2.8-mac-unicode
They are grouped into 5 categories.
它们分为5类。
- /Library/Python/2.6/site-packages/*.egg
- /Library/Python/2.6/site-packages
- Frameworks/Python.framework/Versions/2.6/lib/python2.6
- Frameworks/Python.framework/Versions/2.6/Extras/lib/python
- PATH from PYTHONPATH environment variable.
- /Library/Python/2.6/site-packages/*.egg
- /Library/Python/2.6/site-packages
- 框架/Python.framework/Versions/2.6/lib/python2.6
- 框架/Python.framework/Versions/2.6/Extras/lib/python
- 来自 PYTHONPATH 环境变量的 PATH。
And I can add more paths using the code
我可以使用代码添加更多路径
sys.path.insert(0, MORE_PATH)
- What routines sets up those paths, and when?
- Are some of the paths are built in python source code?
- Is it possible that the paths inserted with 'sys.path.insert' are ignored? I'm curious about this, as with mod_wsgi, I found the paths are not found with 'sys.path.insert'. I asked another postfor this question.
- 哪些例程设置了这些路径,何时设置?
- 一些路径是在python源代码中构建的吗?
- 是否有可能忽略使用“sys.path.insert”插入的路径?我对此很好奇,与 mod_wsgi 一样,我发现“sys.path.insert”找不到路径。我问了另一个帖子这个问题。
ADDED
添加
Based on Michael's answer, I looked into site.py, and I got the following code.
根据迈克尔的回答,我查看了site.py,得到了以下代码。
def addsitepackages(known_paths):
"""Add site-packages (and possibly site-python) to sys.path"""
sitedirs = []
seen = []
for prefix in PREFIXES:
if not prefix or prefix in seen:
continue
seen.append(prefix)
if sys.platform in ('os2emx', 'riscos'):
sitedirs.append(os.path.join(prefix, "Lib", "site-packages"))
elif sys.platform == 'darwin' and prefix == sys.prefix:
sitedirs.append(os.path.join("/Library/Python", sys.version[:3], "site-packages"))
I also think that the directory name that has site.py (/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6 for my Mac) should be built into Python source code.
我还认为应该将包含 site.py 的目录名称(我的 Mac 为 /System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6)构建到 Python 源代码中。
采纳答案by Michael
Most of the stuff is set up in Python's site.pywhich is automatically imported when starting the interpreter (unless you start it with the -Soption). Few paths are set up in the interpreter itself during initialization (you can find out which by starting python with -S).
大多数东西都是在 Python 中设置的site.py,在启动解释器时会自动导入(除非你用-S选项启动它)。在初始化期间,解释器本身设置的路径很少(您可以通过使用 启动python 来找出哪个路径-S)。
Additionally, some frameworks (like Django I think) modify sys.pathupon startup to meet their requirements.
此外,一些框架(如我认为的 Django)会sys.path在启动时进行修改以满足他们的要求。
The sitemodule has a pretty good documentation, a commented source codeand prints out some information if you run it via python -m site.
回答by Andrew Clark
From Learning Python:
从学习 Python:
sys.path is the module search path. Python configures it at program startup, automatically merging the home directory of the top-level file (or an empty string to designate the current working directory), any PYTHONPATH directories, the contents of any .pthfile paths you've created, and the standard library directories. The result is a list of directory name strings that Python searches on each import of a new file.
sys.path 是模块搜索路径。Python 在程序启动时对其进行配置,自动合并顶级文件的主目录(或指定当前工作目录的空字符串)、任何 PYTHONPATH 目录、您创建的任何.pth文件路径的内容以及标准库目录。结果是 Python 在每次导入新文件时搜索的目录名称字符串列表。
回答by nate c
Path has these parts:
路径有这些部分:
- OS paths that have your system libraries
- current directory python started from
- environmental variable
$PYTHONPATH - you can add paths at runtime.
- 具有系统库的操作系统路径
- 当前目录 python 从
- 环境变量
$PYTHONPATH - 您可以在运行时添加路径。
Paths are not ignored. But, they may not be found and that will not raise an error. sys.path should only be added too, not subtracted from. Django would not remove paths.
路径不会被忽略。但是,它们可能找不到,并且不会引发错误。sys.path 也只能添加,而不是从中减去。Django 不会删除路径。
回答by damirv
site.py is indeed the answers. I wanted to remove any dependencies on the old Python that is installed by default on my mac. This works pretty good, as 'site.py' is called each time the python interpreter is started.
site.py 确实是答案。我想删除对 Mac 上默认安装的旧 Python 的任何依赖项。这很有效,因为每次启动 python 解释器时都会调用“site.py”。
For Mac, I manually added the following line at the end of main() in /System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/site.py:
对于 Mac,我在 /System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/site.py 中的 main() 末尾手动添加了以下行:
sys.path = filter (lambda a: not a.startswith('/System'), sys.path)
回答by Robin Macharg
Adding to the accepted answer, and addressing the comments that say a module shouldn't remove entries from sys.path:
添加到已接受的答案,并解决说模块不应从中删除条目的评论sys.path:
This is broadly true but there arecircumstances where you might want to modify sys.pathby removing entries. For instance - and this is Mac-specific; *nix/Windows corollaries may exist - if you create a customised Python.frameworkfor inclusion in your own project you may want to ignore the default sys.pathentries that point at the system Python.framework.
这大体上是正确的,但在某些情况下,您可能希望sys.path通过删除条目来进行修改。例如 - 这是特定于 Mac 的;*nix/Windows 推论可能存在 - 如果您创建一个自定义Python.framework包含在您自己的项目中,您可能希望忽略sys.path指向系统的默认条目Python.framework。
You have a couple of options:
你有几个选择:
Hack the
site.py, as @damirv indicates, orAdd your own
sitecustomizemodule (or package) to the custom framework that achieves the same end result. As indicated in thesite.pycomments (for 2.7.6, anyway):After these path manipulations, an attempt is made to import a module named sitecustomize, which can perform arbitrary additional site-specific customizations. If this import fails with an ImportError exception, it is silently ignored.
破解
site.py,如@damirv指示,或将您自己的
sitecustomize模块(或包)添加到实现相同最终结果的自定义框架中。如site.py评论中所示(无论如何,对于 2.7.6):在这些路径操作之后,尝试导入一个名为 sitecustomize 的模块,该模块可以执行任意附加的特定于站点的自定义。如果此导入失败并出现 ImportError 异常,则它会被静默忽略。
回答by Gilly
Also note: if the PYTHONHOMEenv var is set, standard libraries will be loaded from this path instead of the default, as documented.
另请注意:如果PYTHONHOME设置了env var,将从此路径而不是默认路径加载标准库,如文档所示。
This is not a direct answer to the question, but something I just discovered that was causing the wrong standard libraries to be loaded, and my searches lead me here along the way.
这不是对问题的直接回答,而是我刚刚发现导致加载错误标准库的问题,我的搜索将我带到了这里。
回答by Pierre ALBARèDE
You are using system python /usr/bin/python.
您正在使用系统 python /usr/bin/python。
sys.path is set from system files at python startup.
sys.path 是在 python 启动时从系统文件设置的。
Do not touch those files, in particular site.py, because this may perturb the system.
不要接触这些文件,尤其是 site.py,因为这可能会扰乱系统。
However, you can change sys.path within python, in particular, at startup :
但是,您可以在 python 中更改 sys.path,特别是在启动时:
in ~/.bashrc or ~/.zshrc:
在 ~/.bashrc 或 ~/.zshrc 中:
export PYTHONSTARTUP=~/.pythonrc
export PYTHONSTARTUP=~/.pythonrc
in ~/.pythonrc:
在 ~/.pythonrc 中:
write your changes to sys.path.
将您的更改写入 sys.path。
Those changes will be only for you in interactive shells.
这些更改仅适用于交互式 shell。
For hacking at little risk for the system, install you own and more recent python version.
为了以较小的风险对系统进行黑客攻击,请安装您自己的和更新的 Python 版本。

