我的文件结构如下所示
project
src
__init__.py
main.py
module.py
secondary.py
test
test_module.py
import secondary
x = False
pass
from unittest import TestCase
from src import module
class ModuleTest(TestCase):
def test_module(self):
self.assertTrue(module.x)
调用python3 -m unittest discover
中/project/
给出了一个错误:
File "/Users/Me/Code/project/test/test_module.py", line 6, in <module>
from src import module
File "/Users/Me/Code/project/src/module.py", line 1, in <module>
import secondary
ImportError: No module named 'secondary'
我该怎么办才能将secondary.py
其正确导入?
在Python 3(和带有的Python 2 from __future__ import absolute_import
)中,从同一包中导入另一个模块时,您必须明确要使用哪个模块。您在module.py
(import secondary
)中使用的语法只有secondary
在Python模块搜索路径的文件夹中是顶级模块时才有效。
要从您自己的包中显式请求相对导入,请from . import secondary
改用。或者,利用绝对进口,使用软件包的名称以及模块(from src import secondary
或import src.secondary
并用src.secondary
,而不是其他地方的模块只secondary
)。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句