2016-11-06 63 views
1

僅執行特定的功能,我有兩個文件:如何從另一個文件

test2.py

def fun(): 
    print "from fun" 
print "from test2" 

test.py

from test2 import fun 
print "in text" 
fun() 

我想執行fun功能從test2.py,但我也得到from test2

如何僅使用我想要的功能?

+3

爲什麼你在'test2.py'的頂層的'print'聲明?你可以在if後面加上'if __name__ =='__main__',但爲什麼你需要它呢? – jonrsharpe

回答

3

test2.py您需要確保「從test2」只在程序運行時自動打印。

你可以這樣說:

test2.py

def fun(): 
    print "from fun" 

if __name__ == "__main__": 
    print "from test2" 
相關問題