[英]Importing modules that import other modules from other directories in Python 3.6
[英]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'
我不知道还能做什么。 我试过了:
import PROTOTYPE.Sound_editor.editor
from Sound_editor import editor
以及from Sound_editor.editor import A_class
我还应该尝试什么。 您的专家是否看到任何明显的错误?
更新 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'
任何一个:
from .ant...
没有进入足够的目录或 from editor import A_class
是绝对导入。 Python只会在sys.path
中出现的目录中sys.path
名为editor
的模块。 当您运行main1.py
, Sound_editor
被发现,因为它是在同一目录main1.py
; editor
不是。
您想要的是相对导入,因此可以在以下任何包streamer
找到该editor
:
from .editor import A_class
您可以在运行时添加到 Python 路径:
导入系统
sys.path.insert(1, '/path/to/application/app/folder')
导入文件
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.