Python generates SystemError when trying to import a module into another module

╄→гoц情女王★ 提交于 2019-12-22 14:03:19

问题


I have a file calc.py where I have methods for basic calculations.Now I create another file (in the same directory) called test_calc.py for unittesting the methods in calc.py file.But when I try to run test_calc.py either through command line using

python3 -m unittest test_calc.py

or since I have included name == "main"

python3 test_calc.py

or try to run it directly through the IDE,I get an error that says

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

Below is the screenshot of my project structure

Below is the screenshot of how I import the calc.py file and it accepts the import

This is the code in test_calc.py file which unitests the methods defined in calc.py file

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()

When I run the above code, Python thows error.What is going wrong?


回答1:


You can refer to "Relative imports in Python 3", which suggests, amongst other alternative

python3 -m unittest mypackage.test_calc.py

Try at least to not have a space in your 'unittest module' folder.

See also PEP 366.



来源:https://stackoverflow.com/questions/46752458/python-generates-systemerror-when-trying-to-import-a-module-into-another-module

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!