从 Python 中的模块导入的正确方法,以便它保持可导入和可执行

Proper way to import from a module in Python so that it remains both importable and executable

假设我有 3 个文件:

inc/a.py:

foo = 'bar'

inc/b.py:

from a import foo

c.py:

from inc.b import foo

如果我运行python3 inc/b.py,一切都很好。但是,当我 运行 python3 c.py 时,出现以下错误: ModuleNotFoundError: No module named 'a'.

如果我把inc/b.py改成

from .a import foo

命令 python3 c.py 现在 运行 没问题,但是 python3 inc/b.py 失败 ImportError: attempted relative import with no known parent package

我如何构造代码以使 c.pyinc/b.py 都保持直接可执行?我正在使用 Python 3.9.5.

简短的回答是,将您的 /inc/b.py 编辑为如下所示:

from .a import foo

而不是 运行ning:

python inc/b.py

运行:

python -m inc.b

但是您遇到的这个问题很常见,并且在 post 中回答得非常详细: