2016-09-16 54 views
1

我的項目中沒有任何模塊的組織是這樣的:在我的項目的根文件夾命名爲「XXX」

ezrename/ 
├── base/ 
├── Images/ 
└── shell 

有空瓶在ezrename,底座和外殼文件夾初始化 .py文件。圖像只是一個資源文件夾,沒有任何東西。

我有一個名爲ezrename/base/colors.py的模塊,它實現了Colors類。

我有一個名爲ezrename/shell/baseshell.py的模塊,它實現了BaseShell類並導入了Colors。

from ezrename.base import Colors

,但我得到了以下錯誤:

Traceback (most recent call last): 
    File "/home/devaneando/Development/ezrename/shell/baseshell.py", line 6, in <module> 
    from ezrename.base import Colors 
ImportError: No module named 'ezrename' 

所以我決定嘗試

from ..base import Colors 

,並得到

Traceback (most recent call last): 
    File "/home/devaneando/Development/ezrename/shell/baseshell.py", line 6, in <module> 
    from ..base import Colors 
SystemError: Parent module '' not loaded, cannot perform relative import 

我不知道我在做什麼錯誤。有人可以解釋這些進口是如何工作的,我做什麼不對?

回答

0

通過pythonic的方式,我認爲我的想法是錯誤的。你不能像我想要的那樣從兩個模塊導入,因爲只有當模塊本身沒有導入時,導入纔會起作用,做我想要的是不可能的。

的Python的方式將沒有一個初始化創建一個應用程序文件夾 .py文件,在應用入口腳本導入的包和相關進口將工作:

EzRename 
└──ezrename/ 
    ├── base/ 
    ├── Images/ 
    └── shell 

在EzRename,加application.py:

import ezrename

如果這樣做,shell和base中的類的相對導入將起作用。這是缺少的一塊

0

Python導入將努力形成你的項目的根,所以在模塊的任何進口子目錄應該因此,如果你從baseshell在ezrename /然後導入主模塊運行到

相對進口。 PY應該是:

from base import colors

+0

在反引號中包含你的代碼片段'將它們格式化 - 使讀者更清楚。 – drjimmie1976

+0

感謝您的提示,將盡。 – Jeroanan

+0

謝謝你的回答。 –

0

可以ezrename /鹼添加到Python的路徑,然後只需要導入顏色

如from ezrename/shell/baseshell.py

import os 
import sys 
shell_dir = os.path.dirname(os.path.realpath(__file__)) 
ezrename_dir = os.path.dirname(shell_dir) 
base_dir = os.path.join(ezrename_dir, "base") 
sys.path.append(base_dir) 
import Colors 
+0

謝謝你的回答。 –

相關問題