Python 从导入同级模块的子文件夹导入模块

Python import module from a subfolder that imports a sibling module

提问人:Voelv 提问时间:11/3/2023 最后编辑:Voelv 更新时间:11/3/2023 访问量:43

问:

文件夹结构:

ABC
|--db
|   |-- __init__.py
|   |-- post.py
|   |-- common.py
|   |-- connection.py
|-- __init__.py
|-- main.py

从 main.py 我想将 post.py 导入 db 文件夹。 在 post.py 中,我从 common.py 导入了一些函数。

main.py 内容:from db import post

post.py 内容:from common import table_insert,get_row

运行 main.py 时会出现以下错误:

Traceback (most recent call last):
  File "/home/user/ABC/main.py", line 1, in <module>
    from db import post
  File "/home/user/ABC/db/post.py", line 1, in <module>
    from common import table_insert,get_row
ModuleNotFoundError: No module named 'common'

附加信息:

  • /home/user/ABC 位于 sys.path 中
  • __init__.py文件为空

我尝试在 python 文档中搜索有关如何导入其他模块的一般描述,这些模块反过来又导入其他模块。没有运气.我已经在 Stackoverflow 中搜索了类似的案例 - 没有运气找到任何可用的答案

python 导入 嵌套 同级

评论

0赞 Bibhav 11/3/2023
from .common import table_insert, get_row?

答:

1赞 Bibhav 11/3/2023 #1

在 中,必须使用相对导入:post.py

from .common import table_insert, get_row

相对导入的使用是在与 i.e dir 相同的 dir 中引用。post.pydb

如果你想单独运行,你可以做:

if __name__ == "__main__":
    from common import table_insert,get_row
else:
    from .common import table_insert, get_row

评论

0赞 Voelv 11/3/2023
试过了。根据您的建议单独运行 post.py 给我: From .common import table_insert,get_row ImportError:尝试相对导入,没有已知的父包
0赞 Voelv 11/3/2023 #2

我解决了!

将 post.py 中的 import 语句更改为完全限定语句。

from common import table_insert,get_row

from db.common import table_insert,get_row