尝试将模块导入另一个模块时,Python会生成SystemError

时间:2017-10-15 06:48:16

标签: python-3.x python-import

我有一个文件calc.py,其中我有基本计算方法。现在我创建另一个文件(在同一目录中),名为test_calc.py,用于对calc.py文件中的方法进行单元测试。但是当我尝试运行test_calc时.py通过命令行使用

python3 -m unittest test_calc.py

或者我已经包含名称 ==" 主要"

python3 test_calc.py

或尝试直接通过IDE运行它,我收到一个错误

from . import calc
SystemError: Parent module '' not loaded, cannot perform relative import

以下是我的项目结构的截图

enter image description here

以下是我如何导入calc.py文件并接受导入

的屏幕截图

enter image description here

这是test_calc.py文件中的代码,用于联合calc.py文件中定义的方法

import unittest
from . import calc

class TestCalc(unittest.TestCase):
    def test_add(self):
        result = calc.add(5,2)
        self.assertEqual(result,7)

if __name__ == "__main__":
    unittest.main()

当我运行上面的代码时,Python发生了错误。出了什么问题?

1 个答案:

答案 0 :(得分:0)

你可以参考" Relative imports in Python 3",这表明,以及其他选择

python3 -m unittest mypackage.test_calc.py

至少尝试 not 在您的单元测试模块中留出空格'文件夹中。

另见PEP 366