我有一个像这样的文件夹结构:
api
-- test
-- test_api.py
-- __init__.py
-- api
-- api.py
-- __init__.py
-- sub
-- sub.py
-- __init__.py
sub.py
:
Base = 'base'
api.py
:
from sub.sub import Base
def stuff_to_test(): 通
test_api.py
:
from api.api import stuff_to_test
def test_stuff_to_test():
stuff_to_test()
我在目录api
中。
我运行pytest
:
==================================== ERRORS ====================================
______________________ ERROR collecting tests/test_api.py ______________________
ImportError while importing test module '/<somepath>/api/tests/test_api.py'.
Hint: make sure your test modules/packages have valid Python names.
Traceback:
tests/test_api.py:1: in <module>
from ..api.api import stuff_to_test
api/__init__.py:1: in <module>
from . import api
api/api.py:1: in <module>
from sub.sub import Base
E ImportError: No module named 'sub'
!!!!!!!!!!!!!!!!!!! Interrupted: 1 errors during collection !!!!!!!!!!!!!!!!!!!!
=========================== 1 error in 0.08 seconds ============================
如果我运行python
解释器并从test_api.py
导入内容,也会发生同样的情况:
>>> from tests.test_api import *
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/<somepath>/api/tests/test_api.py", line 1, in <module>
from api.api import stuff_to_test
File "/<somepath>/api/api/__init__.py", line 1, in <module>
from . import api
File "/<somepath>/api/api/api.py", line 1, in <module>
from sub.sub import Base
ImportError: No module named 'sub'
我的第一个想法是在api.py
亲属进行导入:
from .sub.sub import Base
这样测试运行正常。
但如果我运行python api/api.py
,我会收到此错误:
Traceback (most recent call last):
File "api/api.py", line 1, in <module>
from .sub.sub import Base
SystemError: Parent module '' not loaded, cannot perform relative import
我怎样才能运行测试并运行应用程序?
答案 0 :(得分:1)
在python中,有两种方法可以导入模块,具有相对路径或绝对路径。
当您编写BuildImage
时,您正在进行绝对路径导入,对于相对路径导入写入from sub.sub import Base
。
绝对路径导入请查看PYTHONPATH以查找导入的起点,因此您应该写from .sub.sub import Base
。
有关详细信息:Absolute vs. explicit relative import of Python module
答案 1 :(得分:0)
我通过将以下内容添加到test.__init__.py
project_path = os.path.dirname(os.path.dirname(os.path.realpath(__file__)))
api_path= os.path.join(project_path, 'api')
sys.path.append(api_path)