如何从根目录中的模块导入



我有以下项目结构:

root
|--pkg1
|   |--__init__.py
|   |--other_stuff.py
|--stuff.py

在实际的项目中,我在根目录中也有一个测试包
如果我在root上使用python -m unittest运行单元测试,它可以无缝工作。

我想使other_stuff.py模块也可以作为脚本执行。但是,如果我从rootpkg1目录运行它,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 .stufffrom ..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

最新更新