簡體   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