首页 > 解决方案 > 在 Python 中正确管理导入

问题描述

我的问题可能是重复的,但我真的不知道为什么它不能很好地工作。在我的项目中,我有很多单一的测试。对应我们的api,测试是这样写的

mother
--> test_mother
   child1
   --> test_child1
      child2
      --> test_child2

当我进入每个目录单独启动测试时,它工作正常。但是我想从母目录一个接一个地启动所有测试。而且我总是收到错误导入的错误。

在 test_child1 中,我这样做

sys.path.append("../")
from test_mother import Data as data

我懂了:ModuleNotFoundError: No module named 'test_mother'

在孩子2

sys.path.append("../../")
from child1.test_child1 import Data as data

我有这个:ModuleNotFoundError: No module named 'child1'

即使在添加__init__.py目录之后,我也得到了这些错误。

你能解释一下有什么问题以及如何解决吗?

标签: pythonimportdirectoryparent

解决方案


推荐阅读