我在使用Python从相对路径导入模块时遇到了一个问题。我试了所有我在网上找到的。以下是我的目录结构:
starcipher/
__init__.py
caesar.py
tests/
__init__.py
test_caesar.py
如您所知,tests/
目录包含我所有的单元测试。test_caesar.py
使用在caesar.py
中定义的类。这是我的档案:
caesar.py
:
tests/test_caesar.py
:
import unittest
from ..caesar import Caesar
# I also tried:
from caesar import Caesar
from starcipher.caesar import Caesar
from . import Caesar
from .. import Caesar
# Nothing works.
class TestCaesar(unittest.TestCase):
# Blabla
我每次都会犯这个错误:
Traceback (most recent call last):
File "test_caesar.py", line 2, in <module>
from ..caesar import Caesar
SystemError: Parent module '' not loaded, cannot perform relative import
编辑
下面是我如何运行单元测试:
python -m unittest discover tests/
tests/
目录中:python test_caesar.py
python -m unittest
解决方案
多亏了Pocin,从tests/
目录中删除__init__.py
文件解决了这个问题!在
谢谢。在
为了使解决方案很好地可见,修复方法是删除
tests/__init__.py
文件。在不过,我不太清楚为什么会这样,如果有人能解释一下,那就太好了。在
相关问题 更多 >
编程相关推荐