繁体   English   中英

从其他目录导入 python 模块时出现问题?

[英]Problems importing python modules from other directories?

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

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

我以许多不同的形式反复遇到的问题是:
流光.py

from editor import A_class

main1.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: 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 error ModuleNotFoundError: No module named 'ant.base' On乍一看,我从 Github 克隆的库似乎有一些命名问题。 具有相同名称的文件夹和文件听起来像是一场灾难。 当我在这里尝试使用点时:```from .ant.base.ant import Ant``错误

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

任何一个:

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

from editor import A_class是绝对导入。 Python只会sys.path中出现的目录中sys.path名为editor的模块。 当您运行main1.pySound_editor被发现,因为它是在同一目录main1.py ; editor不是。

您想要的是相对导入,因此可以在以下任何包streamer找到该editor

from .editor import A_class

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

some_file.py

导入系统

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

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

导入文件

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM