eclipse 中的相对导入和包结构?

Relative imports and package structure in eclipse?

我在相对导入方面遇到了问题,但我认为这是因为我没有完全理解包结构。

例如,这是我的包结构。

neo_autorig/                          Source folder, Top level
      __init__.py               
      basic/                  Subpackage for basic utiltites for the script
              __init__.py
              name.py

      name_test.py
      module_locator.py

不止于此,但这基本上是我用于导入的内容

在 name.py 中,我正在使用

导入模块定位器
from .. import module_locator

但是它说

# Error: line 1: Attempted relative import beyond toplevel package

顶级脚本(比如我的 main script/ui 用于执行所有内容)是否应该放在 eclipse 包的顶级源文件夹中?还是我设置错了。 source文件夹下还有其他子包,每个子包里面都有脚本。

编辑:如果我将另一个包放在子包中,我可以相对导入,只有在我不能从子包相对导入到顶级包的情况下,脚本源在我的 python路径。

python 导入机制适用于文件的 __name__。直接执行文件会给文件命名 "__main__" 而不是它通常的名字。此类问题的常见答案是 运行 带有 -m 选项的程序。我也推荐阅读 pep 366 and maybe this or this 问题。