Python 3 从包内脚本绝对导入的问题

Issues with Python 3 absolute import from script within package

我觉得这是一个相当基本的问题,所以我只是更难过,因为我已经有一段时间没能解决它了。假设我有以下文件夹结构:

foo
|- first_module.py
|- __init__.py
|- bar
   |- second_module.py
   |- __init__.py

foo 和 bar 是目录。在 first_module.py 中,我有一个引用 second_module.py:

的绝对导入语句
import foo.bar.second_module

现在,如果 运行 first_module.py 作为脚本(foo 是工作目录),我得到这个错误

ModuleNotFoundError: No module named 'foo':

拜托,谁能给我解释一下为什么会这样?我检查过 foo 在 sys.path 中。我已经阅读了 docs 和其他一些 Whosebug 帖子。我认为这可能与解释器不知道 first_module.py 是包 foo 的一部分有关。但是我该如何解决这个问题?

问题是尝试 import foo.bar.second_module 需要您的目录结构有一个 foo 目录作为当前工作目录的子目录,即:

foo
|- first_module.py
|- __init__.py
|- foo
   |- bar
      |- second_module.py  <-- at foo.bar.second_module
      |- __init__.py

要保留您的原始目录结构并成功导入,只需将您的 first_module 更改为使用 import bar.second_module

why this is the case?

importing 时,您应该将点 . 视为类似于路径分隔符。因此,使用以下示例布局:

foo
|- first.py
|- bar
   |- second.py
   |- third.py

如果您想从 first.py import 模块 second.py,您必须写 import bar.second。如果你想从 second 导入 third,你可以写 import third 因为它们都在同一个目录中。

请注意,如果尝试从 first 导入,您仍然需要编写 import bar.third