2013-03-19 90 views
0

我有一個2個文件。Python導入到另一個模塊時正在打印所有表單模塊

  1. funcattrib.py
  2. test_import.py

funcattrib.py

import sys 

def sum(a,b=5): 
    "Adds two numbers" 
    a = int(a) 
    b = int(b) 
    return a+b 

sum.version = "1.0" 
sum.author = "Prasad" 
k = sum(1,2) 
print(k) 

print("Function attributes: - ") 
print("Documentation string:",sum.__doc__) 
print("Function name:",sum.__name__) 
print("Default values:",sum.__defaults__) 
print("Code object for the function is:",sum.__code__) 
print("Dictionary of the function is:",sum.__dict__) 

#writing the same information to a file 

f = open('test.txt','w') 
f.write(sum.__doc__) 
f.close() 
print("\n\nthe file is successfully written with the documentation string") 

test_import.py

import sys 
from funcattrib import sum 

input("press <enter> to continue") 

a = input("Enter a:") 
b = input("Enter b:") 
f = open('test.txt','a') 
matter_tuple = "Entered numbers are",a,b 
print(matter_tuple) 
print("Type of matter:",type(matter_tuple)) 
matter_list = list(matter_tuple) 
print(list(matter_list)) 
finalmatter = " ".join(matter_list) 
print(finalmatter) 
f.write(finalmatter) 
f.close() 
print("\n\nwriting done successfully from test_import.py") 

我從funcattrib.py進口sum功能。當我嘗試執行test_import.py時,我看到整個funcattrib.py的輸出。我只是想使用sum函數。

請指教,我做錯了什麼,或者是有進口模塊,而不實際執行它的另一種方式?

回答

4

導入時會執行模塊「頂層」中的所有語句。

你你不要想要發生,你需要區分被用作腳本和模塊的模塊。使用下面的測試爲:

if __name__ == '__main__': 
    # put code here to be run when this file is executed as a script 

應用,爲您的模塊:

import sys 

def sum(a,b=5): 
    "Adds two numbers" 
    a = int(a) 
    b = int(b) 
    return a+b 

sum.version = "1.0" 
sum.author = "Prasad" 

if __name__ == '__main__': 
    k = sum(1,2) 
    print(k) 

    print("Function attributes: - ") 
    print("Documentation string:",sum.__doc__) 
    print("Function name:",sum.__name__) 
    print("Default values:",sum.__defaults__) 
    print("Code object for the function is:",sum.__code__) 
    print("Dictionary of the function is:",sum.__dict__) 

    #writing the same information to a file 

    f = open('test.txt','w') 
    f.write(sum.__doc__) 
    f.close() 
    print("\n\nthe file is successfully written with the documentation string") 
+0

真棒人。感謝超級快速回復。有效。 – 2013-03-19 19:53:06

2

Python的執行從上到下,始終。函數定義與其他任何東西一樣是可執行代碼當您導入模塊時,全部運行該模塊頂層的代碼。 Python必須全部運行,因爲函數是代碼的一部分。

的解決方案是爲保護代碼,你不想要一個if __name__=="__main__"塊下的進口運行:

if __name__ == "__main__": 
    print("Some info")