无法从相对路径导入模块

2024-10-01 02:31:48 发布

您现在位置:Python中文网/ 问答频道 /正文

我在使用Python从相对路径导入模块时遇到了一个问题。我试了所有我在网上找到的。以下是我的目录结构:

starcipher/
    __init__.py
    caesar.py
    tests/
        __init__.py
        test_caesar.py

如您所知,tests/目录包含我所有的单元测试。test_caesar.py使用在caesar.py中定义的类。这是我的档案:

caesar.py

^{pr2}$

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文件解决了这个问题!在

谢谢。在


Tags: 模块frompytestimport目录inittests