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

2024-06-25 23:04:00 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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
切普纳建议使用相对导入from .editor import A_class。这是成功的,但引起了另一个需要阐述的问题

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

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

要么:

  1. from .ant...上的目录不够,或者
  2. 名为ant的文件/文件夹混淆了命令

Tags: 文件frompyimport目录nodebaseinit
2条回答

您可以在运行时将以下内容添加到Python路径:

some_file.py

导入系统

insert位于1,0是脚本路径(或REPL中的“”)

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

导入文件

from editor import A_class是绝对重要的。Python将sys.path中出现的目录中查找名为editor的模块。运行main1.py时,会找到Sound_editor,因为它与main1.py位于同一目录中editor不是

您需要的是一个相对导入,这样editor就可以在任何包streamer中找到:

from .editor import A_class

相关问题 更多 >