【问题标题】:Python generates SystemError when trying to import a module into another module尝试将模块导入另一个模块时,Python 会生成 SystemError
【发布时间】:2017-10-15 06:48:16
【问题描述】:

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

python3 -m unittest test_calc.py

或者因为我已经包含了 name == "ma​​in"

python3 test_calc.py

或者尝试直接通过IDE运行它,我得到一个错误提示

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

下面是我的项目结构截图

以下是我如何导入 calc.py 文件并接受导入的屏幕截图

这是 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 抛出错误。出了什么问题?

【问题讨论】:

    标签: python-3.x python-import


    【解决方案1】:

    您可以参考“Relative imports in Python 3”,其中包括其他选择

    python3 -m unittest mypackage.test_calc.py
    

    尝试至少在您的“单元测试模块”文件夹中有空间。

    另见PEP 366

    【讨论】:

    • "尽量不要在您的 'unittest module' 文件夹中留有空间。" --- 这解决了问题!再次感谢!
    • 我将文件夹重命名为 unittest_module.So 而不是从 . import calc,我是从 unittest_module import calc 做的,它起作用了。
    猜你喜欢
    • 2010-11-11
    • 2018-04-23
    • 1970-01-01
    • 1970-01-01
    • 2022-01-08
    • 1970-01-01
    • 1970-01-01
    • 2020-05-18
    • 1970-01-01
    相关资源
    最近更新 更多