[英]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.