我试图遵循PEP 328,其目录结构如下:

pkg/
  __init__.py
  components/
    core.py
    __init__.py
  tests/
    core_test.py
    __init__.py

在core_test.py中,我有以下import语句

from ..components.core import GameLoopEvents

然而,当我运行时,我得到以下错误:

tests$ python core_test.py 
Traceback (most recent call last):
  File "core_test.py", line 3, in <module>
    from ..components.core import GameLoopEvents
ValueError: Attempted relative import in non-package

四处搜索,我发现“相对路径即使使用__init__.py也无法工作”和“从相对路径导入模块”,但它们都没有帮助。

这里有什么我遗漏的吗?


当前回答

这里有一种方法会惹恼所有人,但效果很好。在测试运行中:

ln -s ../components components

然后像往常一样导入组件。

其他回答

您可以使用from pkg.components.core导入GameLoopEvents,例如,我使用pycharm,下面是我的项目结构图,我只是从根包导入,然后就可以了:

这种方法对我有效,比一些解决方案更不杂乱:

try:
  from ..components.core import GameLoopEvents
except ValueError:
  from components.core import GameLoopEvents

父目录位于我的PYTHONPATH中,父目录和此目录中有__init__.py文件。

上面的方法在python 2中总是有效的,但是python 3有时会遇到ImportError或ModuleNotFoundError(后者在python 3.6中是新的,也是ImportError的一个子类),所以下面的调整对我在python 2和3中都有效:

try:
  from ..components.core import GameLoopEvents
except ( ValueError, ImportError):
  from components.core import GameLoopEvents

由于您已经将所有内容标记为模块,因此如果您作为python模块启动,则无需使用相对引用。

而不是

from ..components.core import GameLoopEvents

仅仅

from pkg.components.core import GameLoopEvents

当您从pkg的父级运行时,请使用以下命令

python -m pkg.tests.core_test

这里有一种方法会惹恼所有人,但效果很好。在测试运行中:

ln -s ../components components

然后像往常一样导入组件。

如果您的项目结构如下所示:

   project
     |
     | --- module1
     |      |
     |      file1.py
     |
     |-----module2
     |     |
     |     file2.py

您将从file2.py中导入file1.py,您可以在file2.py中执行此操作:

import sys
sys.path.append('.')

import file2

我仍然不知道为什么和怎么做,但这对我有用。