PYTHONPATH 与 sys.path [英] PYTHONPATH vs. sys.path
问题描述
另一位开发人员和我不同意是否应该使用 PYTHONPATH
或 sys.path
来允许 Python 在用户(例如,开发)目录中查找 Python 包.
Another developer and I disagree about whether PYTHONPATH
or sys.path
should be used to allow Python to find a Python package in a user (e.g., development) directory.
我们有一个具有典型目录结构的 Python 项目:
We have a Python project with a typical directory structure:
Project
setup.py
package
__init__.py
lib.py
script.py
在script.py中,我们需要做import package.lib
.当包安装在site-packages中时,script.py可以找到package.lib
.
In script.py, we need to do import package.lib
. When the package is installed in site-packages, script.py can find package.lib
.
然而,当从用户目录工作时,还需要做一些其他的事情.我的解决方案是将我的 PYTHONPATH
设置为包含 "~/Project"
.另一个开发者想把这行代码放在script.py的开头:
When working from a user directory, however, something else needs to be done. My solution is to set my PYTHONPATH
to include "~/Project"
. Another developer wants to put this line of code in the beginning of script.py:
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
这样 Python 就可以找到 package.lib
的本地副本.
So that Python can find the local copy of package.lib
.
我认为这是一个坏主意,因为这条线仅对开发人员或从本地副本运行的人有用,但我无法给出一个很好的理由为什么这是一个坏主意.
I think this is a bad idea, as this line is only useful for developers or people running from a local copy, but I can't give a good reason why it is a bad idea.
我们应该使用PYTOHNPATH
、sys.path
,还是两者都可以?
Should we use PYTOHNPATH
, sys.path
, or is either fine?
推荐答案
如果修改路径的唯一原因是开发人员在他们的工作树中工作,那么您应该使用安装工具为您设置环境.virtualenv 非常流行,如果你正在使用 setuptools,你可以简单地运行 setup.py develop
在你当前的 Python 安装中半安装工作树.
If the only reason to modify the path is for developers working from their working tree, then you should use an installation tool to set up your environment for you. virtualenv is very popular, and if you are using setuptools, you can simply run setup.py develop
to semi-install the working tree in your current Python installation.
这篇关于PYTHONPATH 与 sys.path的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!