我有以下项目结构:
root
|--pkg1
| |--__init__.py
| |--other_stuff.py
|--stuff.py
在实际的项目中,我在根目录中也有一个测试包
如果我在root
上使用python -m unittest
运行单元测试,它可以无缝工作。
我想使other_stuff.py
模块也可以作为脚本执行。但是,如果我从root
或pkg1
目录运行它,Python解释器会返回以下错误:
Traceback (most recent call last):
File "pkg1/other_stuff.py", line 1, in <module>
from stuff import Dummy
ModuleNotFoundError: No module named 'stuff'
这是代码:
# file pkg1/__init__.py
# (empty)
# file pkg1/other_stuff.py
from stuff import Dummy
if __name__ == '__main__':
# do other stuff
pass
# file stuff.py
class Dummy:
pass
我还尝试了相对导入from .stuff
和from ..stuff
的包,但它给出了错误:
Traceback (most recent call last):
File "pkg1/other_stuff.py", line 1, in <module>
from ..stuff import Dummy
ImportError: attempted relative import with no known parent package
我不习惯Python3导入系统
在other_stuff.py
中导入stuff.py
以使其在测试和脚本中都能工作的正确方法是什么?
我找到了一个可能不是最好的解决方案,但它确实有效。要将other_stuff.py
作为脚本运行,我只需要打开root
目录中的终端并运行python3 -m pkg1.other_stuff
。