2013-03-19 118 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")