【发布时间】:2015-11-24 12:21:06
【问题描述】:
- Python 2.7.10
- 在虚拟环境中
- 在每个模块中启用
from __future__ import absolute_import
目录树如下:
Project/
prjt/
__init__.py
pkg1/
__init__.py
module1.py
tests/
__init__.py
test_module1.py
pkg2/
__init__.py
module2.py
tests/
__init__.py
test_module2.py
pkg3/
__init__.py
module3.py
tests/
__init__.py
test_module3.py
data/
log/
我尝试在pkg1/module1.py 中使用compute() 的函数compute(),方法如下:
# In module1.py
import sys
sys.path.append('/path/to/Project/prjt')
from prjt.pkg2.module2 import compute
但是当我运行 python module1.py 时,解释器引发了 No module named prjt.pkg2.module2 的 ImportError。
- “绝对导入”的正确方式是什么?我必须将
Project的路径添加到sys.path吗? - 如何在交互式解释器中运行
test_module1.py?通过python prjt/pkg1/tests/test_module1.py或python -m prjt/pkg1/tests/test_module1.py?
【问题讨论】:
-
是的,如果您在导入中引用项目,项目需要在路径上。否则只需
from pkg2.module2...等。 -
@DanielRoseman 谢谢。您能否说明“其他”情况?
标签: python python-2.7 python-import