我需要PYTHONPATH吗 [英] Do I need PYTHONPATH
问题描述
关于PYTHONPATH和导入有很多类似的问题,但是我没有找到我真正需要的东西.
There are many of similar questions about PYTHONPATH and imports but I didn't find exactly what I needed.
我有一个git存储库,其中包含一些python帮助程序脚本.这些脚本自然地组织在几个软件包中.像这样:
I have a git repository that contains a few python helper scripts. The scripts are naturally organized in a few packages. Something like:
scripts/main.py
scripts/other_main.py
scripts/__init__.py
a/foo.py
a/bar.py
a/__init__py
b/foo.py
b/bar.py
b/__init__.py
__init__.py
脚本
取决于 a
和 b
.我在所有模块中都使用绝对导入.我运行 python3 scripts/main.py
.只要将 PYTHONPATH
设置为项目的根,一切都可以正常工作.
scripts
depends on a
and b
. I'm using absolute import in all modules. I run python3 scripts/main.py
. Everything works as long as I set up PYTHONPATH
to the root of my project.
但是,我想避免用户设置环境变量的麻烦.
However, I'd like to avoid users the hassle of setting up an environment variable.
正确的方法是什么?我希望这可以像在Java中那样工作,默认情况下,当前目录默认位于类路径中,但事实并非如此.我还尝试了相对导入,但没有成功.
What would be the right way to go? I expected this to work like in java, where the current dir is in the classpath by default but it doesn't seem to be the case. I've also tried relative import without success.
如果我删除顶级 __ init __.py
推荐答案
首先,您是对的,因为我认为您不需要顶级的 __ init __.py
.删除它并不能解决我的任何导入错误.
Firstly, you're right in that I don't think you need the top-level __init__.py
. Removing it doesn't solve any import error for me though.
您不需要设置PYTHONPATH,我可以想到一些替代方法:
You won't need to set PYTHONPATH and there are a few alternatives that I can think of:
-
使用虚拟环境( https://virtualenv.pypa.io/en/最新/).这还需要您将代码打包到可安装的软件包中( https://packaging.python.org/).由于该选项与您的问题没有直接关系,因此我将不做进一步解释.
Use a virtual environment (https://virtualenv.pypa.io/en/latest/). This would also require you to package up your code into an installable package (https://packaging.python.org/). I won't explain this option further since it's not directly related to your question.
将模块移动到 scripts
目录下.Python自动将脚本的目录添加到Python路径中.
Move your modules under your scripts
directory. Python automatically adds the script's directory into the Python path.
在脚本中修改 sys.path
变量,以便它们可以找到您的本地模块.
Modify the sys.path
variable in your scripts so they can find your local modules.
第二个选项是最简单的.
The second option is the most straightforward.
第三个选项将要求您在正常导入的之上的脚本顶部添加一些python代码.在您的 main.py
中,它看起来像:
The third option would require you to add some python code to the top of your scripts, above your normal imports. In your main.py
it would look like:
#!/usr/bin/env python
import os.path, sys
sys.path.insert(0, os.path.dirname(os.path.dirname(__file__)))
import a
import b
这是什么:
-
获取脚本的文件名
Take the filename of the script
计算脚本目录的父目录
将该目录添加到 sys.path
然后正常导入模块
这篇关于我需要PYTHONPATH吗的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!