Python 尝试将一个模块导入另一个模块时生成 SystemError
Python generates SystemError when trying to import a module into another module
我有一个文件 calc.py,其中有基本的方法 calculations.Now 我创建了另一个名为 test_calc.py 的文件(在同一目录中),用于对 [=39 中的方法进行单元测试=] file.But 当我尝试 运行 test_calc.py 通过命令行使用
python3 -m unittest test_calc.py
或者因为我包含了 name == "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怎么error.What出错了?
你可以参考“Relative imports in Python 3”,这表明,除其他选择外
python3 -m unittest mypackage.test_calc.py
至少尝试 不要 在您的 'unittest module' 文件夹中有一个 space。
另见 PEP 366。
我有一个文件 calc.py,其中有基本的方法 calculations.Now 我创建了另一个名为 test_calc.py 的文件(在同一目录中),用于对 [=39 中的方法进行单元测试=] file.But 当我尝试 运行 test_calc.py 通过命令行使用
python3 -m unittest test_calc.py
或者因为我包含了 name == "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怎么error.What出错了?
你可以参考“Relative imports in Python 3”,这表明,除其他选择外
python3 -m unittest mypackage.test_calc.py
至少尝试 不要 在您的 'unittest module' 文件夹中有一个 space。
另见 PEP 366。