python - 如何使用 Python 从嵌套子目录导入内容?

标签 python

在我的主文件(根级别)中,我有:

from deepspeech2_utils import reduce_tensor, check_loss

我还有一个 __init__.py ,其中包含:

from submodules.deepspeech2 import utils as deepspeech2_utils

我的目录结构如下所示:

main.py
__init__.py
-submodules
  -deepspeech2
    -utils.py

但是我收到一个错误:

    from deepspeech2_utils import reduce_tensor, check_loss
ImportError: No module named deepspeech2_utils

我也尝试过:

from submodules.deepspeech2.utils import reduce_tensor, check_loss

但得到同样的错误。

我做错了什么?

最佳答案

因此,在 python 中,目录被识别为模块的方式是通过这些目录中存在 __init__.py 文件。这些 __init__.py 文件不需要有代码。因此,将目录结构更改为如下所示

root
    main.py
    __init__.py
    submodules
        __init__.py
        deepspeech2
            __init__.py
            utils.py

现在,一旦完成,您的导入语句 (如果没有上述目录更改,则无法工作)__init__.py 中有一个作用域,它在您的 main.py 中不可见 - 具有不同的作用域。为了实现您正在做的事情,请将 main.py 中的导入语句更改为

从root.deepspeech2_utils导入reduce_tensor,check_loss

除了命名空间原因之外,我还必须建议,不鼓励在 __init__.py 中导入,因为模块的用户可能只想从模块/子模块和导入语句中导入特定的内容__init__.py 将迫使他们导入比他们想要的更多的导入。 Here is an answer来自另一篇详细讨论此类问题的帖子

关于python - 如何使用 Python 从嵌套子目录导入内容?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61044688/

相关文章:

python - 使用 openpyxl 在 Excel 工作表中的文本字符串中搜索单词

python - 使用 pytest mocker 忽略assert_has_calls中的链式调用

python - 电子邮件消息 python 抓取消息的一部分

python - BeautifulSoup 将表头复制到页脚

python - 将 C 枚举位域转换为 Python

python - 类型错误 : __init__() takes exactly 1 argument (3 given) pyXML

python - 无法在 keras 中连接两个输入层。

python - wav 文件幅度计算

python - NetCDF 大数据

python - 如何对 Python 程序进行版本控制