2013-03-19 3 views
0

2 개의 파일이 있습니다.다른 모듈로 가져올 때 파이썬이 모든 모듈을 인쇄합니다.

  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

멋진 사람 :

이 솔루션은 당신이 if __name__=="__main__" 블록에서 수입에 실행을 원하지 않는 코드를 보호하는 것입니다. 슈퍼 빠른 답장을 보내 주셔서 감사합니다. 그것은 효과가 있었다. –

2

파이썬은 항상 위에서 아래로 실행됩니다. 함수 정의는 다른 어떤 것과 마찬가지로 실행 가능한 코드입니다. 모듈을 가져올 때 모두 해당 모듈의 최상위 수준에있는 코드가 실행됩니다. 함수는 코드의 일부이기 때문에 파이썬은 그것을 모두 실행해야합니다.

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