在尝试将一个模块导入到另一个模块时,Python会生成系统错误 [英] Python generates SystemError when trying to import a module into another module

查看:10
本文介绍了在尝试将一个模块导入到另一个模块时,Python会生成系统错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

python3 -m unittest test_calc.py

或因为我添加了名称=="main"

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显示错误。出什么问题了?

推荐答案

您可以参考"Relative imports in Python 3",其中建议

python3 -m unittest mypackage.test_calc.py

至少尝试不要在"unittest模块"文件夹中留出空间。

另请参阅PEP 366

这篇关于在尝试将一个模块导入到另一个模块时,Python会生成系统错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆