【问题标题】:Problems importing python modules from other directories?从其他目录导入 python 模块时出现问题?
【发布时间】:2021-09-27 07:04:28
【问题描述】:

我的项目越来越大,正确的模块无法正确导入。结果是程序在第一行停止运行。这是我的目录映射当前的样子:

PROTOTYPE
- Sound_editor (folder)
- - openant (cloned library from Github)
- - - __init__.py
- - - (a bunch of files and folders from the library)

**
- - - ant
- - - - base
- - - - - ant.py
- - - - - __init__.py
- - - - easy
- - - - - __init__.py
- - - - - node.py
**

- - - demo.py

- - __init__.py
- - editor.py
- - reader.py
- - streamer.py
- - main2.py

- main1.py

我以多种不同形式反复遇到的问题是:
streamer.py

from editor import A_class

ma​​in1.py

import Sound_editor.streamer

当我运行 main1.py 时,它首先导入流光文件。然后流媒体文件尝试导入编辑器文件但失败。 错误

ModuleNotFoundError: No module named 'editor'

我不知道还能做什么。我试过了:

  1. 本指南中有很多内容:https://chrisyeh96.github.io/2017/08/08/definitive-guide-python-imports.html
  2. 点我通往正确道路的变体:import PROTOTYPE.Sound_editor.editor
  3. 使用来自:from Sound_editor import editor 以及 from Sound_editor.editor import A_class
  4. 我研究过这个答案:Importing files from different folder。我不确定他将目录构建为一个包是什么意思。我已经添加了 init.py 文件。 (它们是空的..)

我还应该尝试什么。专家们有没有发现任何明显的错误?

更新 1
chepner 建议相对导入。 from .editor import A_class。这是成功的,但导致了另一个需要阐述的问题。

streamer.py 也有以下导入:from .openant.ant.easy.node import Node 但节点也有导入: node.py from ant.base.ant import Ant 错误 ModuleNotFoundError: No module named 'ant.base' 乍一看,我从 Github 克隆的库似乎有一些命名问题。同名的文件夹和文件听起来就像一场灾难。当我在这里尝试使用点时: ```从.ant.base.ant导入蚂蚁` 错误

ModuleNotFoundError: No module named 'Sound_editor.openant.ant.easy.ant'

要么:

  1. from .ant... 没有足够的目录或
  2. 名为 ant 的文件/文件夹混淆了命令...??

【问题讨论】:

    标签: python import directory


    【解决方案1】:

    from editor import A_class 是绝对导入。 Python 将在出现在 sys.path 中的目录中查找名为 editor 的模块。当你运行main1.py时,会找到Sound_editor,因为它和main1.py在同一个目录下; editor 不是。

    您想要的是相对导入,以便在 streamer 本身所在的任何包中找到 editor

    from .editor import A_class
    

    【讨论】:

    • 进口链中出现了另一个相关问题。在 cmets 中添加的信息太多,因此请检查 update1。我还更新了我概述的目录。你让我超越了链条中的第一个环节。
    • 软件包中是否缺少 __init__.py 文件,或者您是否为了简洁而在问题中省略了它们?例如,没有easy/__init__.pyeasy 就不是一个模块。
    • 非常简单地说:一个包是一个可以(或确实;我不确定是否有区别)包含其他模块的模块。可以从包含__init__.py 文件的文件或目录创建模块。
    • 为简洁起见,我省略了 /__init__.py。刚刚将它们添加到主帖中
    • 还有ant/?需要__init__.py的不仅仅是“终端”目录; 所有目录都需要它们。
    【解决方案2】:

    您可以在运行时添加到 Python 路径:

    some_file.py

    导入系统

    在 1 处插入,0 是脚本路径(或 REPL 中的 '')

    sys.path.insert(1, '/path/to/application/app/folder')

    导入文件

    【讨论】:

      猜你喜欢
      • 2017-08-20
      • 2019-09-07
      • 1970-01-01
      • 2020-02-21
      • 1970-01-01
      • 2011-02-19
      • 2013-07-26
      • 2018-01-03
      • 2017-10-05
      相关资源
      最近更新 更多