2013-12-10 41 views
2

我的包結構導入包模塊是:如何從包「主」模塊

 
main.py 
mapp/ 
    __init__.py 
    core/ 
    __init__.py 
    tobeimported.py 
    test/ 
    __init__.py 
    (test modules) 
    utils/ 
    __init__.py 
    blasttofasta.py 

文件blasttofasta.py作爲腳本執行。

blasttofasta.py樣子:

import mapp.core.tobeimported 

def somefunc(): 
    pass 


if __name__ == '__main__': 
    pass 

但出現異常:

Traceback (most recent call last): 
    File "utils/blasttofasta.py", line 5, in <module> 
    import mapp.core.tobeimported 
ImportError: No module named mapp.core.analyzers 

如何導入 tobeimported模塊?我運行從頂部目錄blastofofasta.py(其中main.py是)

編輯:也許更好的問題是:如何獲得mapp包到sys.path?因爲腳本文件只能看到它自己的目錄而不能看到軟件包目錄。

謝謝

+0

python -m mapp.utils.test << This works。但我不知道它爲什麼可行,而經典的python mapp/utils/test.py沒有。 – Karlvonbahnhof

回答

1

如果我想要包括blasttofasta.py或同時運行腳本mos重要的是要有包含在sys.path中的mapp包的目錄。

這爲我工作:

(從這個包或其他模塊)進口MAPP之前我寫到blasttofasta.py:

import os 
os.sys.path.append(os.path.dirname(os.path.realpath(__file__))+ '/../../') 

這追加MAPP包路徑,我可以運行它作爲腳本。另一方面沒有問題被包含在另一個包中。

0

按照絕對結構導入。

要導入blasttofasta.py在tobeimport.py

ToBeimport內容

from myapp.utils import blasttofasta 

您的結構良好。

+0

修復你的格式:) –

+0

我給了錯誤:ImportError:沒有名爲mapp.utils.common的模塊 – Karlvonbahnhof

0

有兩件事情需要發生:

你可以簡單地做到這一點(天真):

$ touch /path/to/map/__init__.py 
  • /path/to/map需要在sys.path

請仔細閱讀。

+0

如果我從包含mapp包的目錄運行blasttofasta.py,那麼它在sys.path中,不是嗎? – Karlvonbahnhof

+0

編號默認情況下,Python只將**當前工作目錄**添加到''sys.path''和任何**安裝的包**。請閱讀我發佈的鏈接。 –

+0

我試了一下。如果我讓python show cwd(通過os.getcwd())顯示包含mapp包的目錄。這不對嗎? – Karlvonbahnhof