如何在python中引用子模块

时间:2019-05-18 22:50:19

标签: python python-3.x

我具有以下结构。

enter image description here

以下是来自call_module1_module2.py的代码。这很好。我可以同时引用这两个模块。

from module1.file1 import *
from module2.file2 import *

function1()
function2()

但是,当我尝试使用下面的代码从module2的file2.py中调用module1文件夹的file1.py中的function1时

from tmodules.module1.file1 import *

我收到一条错误消息,未找到模块“ tmodules”。这是父文件夹/项目的名称。

我想念什么?所有 init .py均为空。我应该在该文件中添加任何内容吗?

1 个答案:

答案 0 :(得分:0)

我通常使用的两种解决方案:  1)从根文件夹中引用子模块,例如:

from top_module.child_folder.some_submodule import some_function

2)如果您位于下方一级,则可以执行以下操作:

from ..parent_folder.some_submodule import some_function

2bis)如果您位于同一文件夹中,则:

from .hello_brother_module import some_function

您也可以将路径添加到sys.path,但我个人认为该解决方案不完善