Python으로 sys.path를 설정하는 것은 무엇이며 언제입니까?
내가 달릴 때
import sys
print sys.path
내 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
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
- PYTHONPATH 환경 변수의 PATH입니다.
그리고 코드를 사용하여 더 많은 경로를 추가 할 수 있습니다.
sys.path.insert(0, MORE_PATH)
- 이러한 경로를 설정하는 루틴은 무엇이며 언제입니까?
- 일부 경로는 Python 소스 코드로 빌드됩니까?
- 'sys.path.insert'로 삽입 된 경로가 무시 될 수 있습니까? mod_wsgi와 마찬가지로 'sys.path.insert'에서 경로를 찾을 수 없다는 것이 궁금합니다. 이 질문에 대한 다른 게시물 을 요청했습니다 .
추가됨
Michael의 답변을 바탕으로 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"))
또한 site.py (Mac의 경우 /System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6)가있는 디렉토리 이름이 Python 소스 코드에 빌드되어야한다고 생각합니다.
대부분의 항목은 site.py
인터프리터를 시작할 때 자동으로 가져 오는 Python에서 설정됩니다 ( -S
옵션으로 시작하지 않는 한 ). 초기화하는 동안 인터프리터 자체에 설정되는 경로는 거의 없습니다 (파이썬을 시작하여 찾을 수 있습니다 -S
).
Additionally, some frameworks (like Django I think) modify sys.path
upon startup to meet their requirements.
The site
module has a pretty good documentation, a commented source code and prints out some information if you run it via python -m site
.
From Learning 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 .pth file 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.
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.
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:
sys.path = filter (lambda a: not a.startswith('/System'), sys.path)
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.
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.
Adding to the accepted answer, and addressing the comments that say a module shouldn't remove entries from sys.path
:
This is broadly true but there are circumstances where you might want to modify sys.path
by removing entries. For instance - and this is Mac-specific; *nix/Windows corollaries may exist - if you create a customised Python.framework
for inclusion in your own project you may want to ignore the default sys.path
entries that point at the system Python.framework
.
You have a couple of options:
Hack the
site.py
, as @damirv indicates, orAdd your own
sitecustomize
module (or package) to the custom framework that achieves the same end result. As indicated in thesite.py
comments (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.
Also note: if the PYTHONHOME
env var is set, standard libraries will be loaded from this path instead of the default, as documented.
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.
You are using system python /usr/bin/python
.
sys.path is set from system files at python startup.
Do not touch those files, in particular site.py, because this may perturb the system.
However, you can change sys.path within python, in particular, at startup :
in ~/.bashrc or ~/.zshrc:
export PYTHONSTARTUP=~/.pythonrc
in ~/.pythonrc:
write your changes to sys.path.
Those changes will be only for you in interactive shells.
For hacking at little risk for the system, install you own and more recent python version.
참고URL : https://stackoverflow.com/questions/4271494/what-sets-up-sys-path-with-python-and-when
'programing tip' 카테고리의 다른 글
클립 보드에 데이터를 안전하게 복사하기위한 플래시 기반 ZeroClipboard의 HTML5 대안? (0) | 2020.11.22 |
---|---|
Entity Framework에서 외래 키 관계를 추가하는 방법은 무엇입니까? (0) | 2020.11.22 |
Firebase 실시간 데이터베이스에 해당하는 AWS는 무엇입니까? (0) | 2020.11.22 |
자산 카탈로그 pathForResource에 액세스 (0) | 2020.11.22 |
RDP 클라이언트가 데스크톱이 아닌 원격 애플리케이션을 시작할 수 있습니까? (0) | 2020.11.22 |