2017-04-26 105 views
0

我想從模塊abc.py 中導入函數foo()但是,abc.py包含其他函數,這些函數依賴於Python不可用的模塊(即,我不能將它們導入到Python解釋器,因爲我用的ImageJ爲Jython的運行abc.py)從沒有模塊依賴的模塊中導入函數

一個解決方案,我發現是把有問題的進口名內 ==「主要」檢查,如:

# abc.py 
def foo(): 
    print("Hello, World!") 

def run_main_function(): 
    foo() 
    ...other stuff using IJ... 

if __name__ == "__main__": 
    from ij import IJ 
    run_main_function() 

所以當我嘗試t o將foo從另一個腳本def.py中導入,例如:

# def.py 
from abc import foo 

def other_func(): 
    foo() 

if __name__ == "__main__": 
    other_func() 

這是有效的。但是當我以正常的方式放置導入時,在腳本的頂部,出現錯誤:沒有名爲'ij'的模塊。我想知道是否有解決這個問題的辦法?特別是,我把進口放在腳本的頂部,然後在def.py中,我說只導入函數,而不依賴於abc.py?

回答

0

您不應在import聲明中包含.py擴展名。它應該閱讀:

from abc import foo 
+0

當然,寫這個問題時這是一個類型/省略,謝謝指出。 – MMagician

0

I would like to know if there is a solution to this problem? Specifically, that I put the imports at the top of the script and then within def.py I say to import just the function, without dependencies of abc.py?

據我所知,那就是蟒蛇的工作方式。您應該將該導入放入使用它的函數中,否則始終無法使用。

def run_main_function(): 
    from ij import IJ 
    foo() 

另外,不要使用abc爲模塊名,這是一個標準庫模塊:Abstract Base Class 2.7Abstract Base Class 3.6

編輯:不要使用作爲Kind Stranger導入時表示尾隨.py