Python:在祖父母目录中导入文件 [英] Python: Import file in grandparent directory
问题描述
层次结构:
scripts/
web/
script1.py
tests/
script2.py
common/
utils.py
我将如何在脚本1和脚本2中导入utils,并且仍然能够分别运行这些脚本(即python script1.py
).我将__init__.py
文件放在哪里,这是解决此问题的正确方法吗?谢谢!
How would I import utils in script1 and script2, and still be able to run those scripts seperately (i.e., python script1.py
). Where would I place the __init__.py
files, and is that the correct way to go about this? Thank you!
推荐答案
package/
__init__.py
scripts/
web/
__init__.py
script1.py
tests/
__init__.py
script2.py
common/
__init__.py
utils.py
我已将一堆空的__init__.py
文件添加到您的程序包中.现在,您有2个选择,可以使用绝对导入:
I've added a bunch of empty __init__.py
files to your package. Now you have 2 choices, you can use an absolute import:
from package.common import utils
或等效地:
import package.common.utils as utils
这里的缺点是package
必须以某种方式位于PYTHONPATH
上.另一个选择是使用相对导入:
The downside here is that package
must somehow be on PYTHONPATH
. The other option is to use relative imports:
from ....common import utils
我通常不鼓励这种方法...很难说出事情的来龙去脉(是4个周期还是6个周期?).
I would generally discourage this approach... It just gets too hard to tell where things are coming from (is that 4 periods or 6?).
这篇关于Python:在祖父母目录中导入文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!