2017-09-21 2 views

답변

1

StringIO를 사용하고 표준 출력을 문자열로 캡처 할 수 있습니다.

from io import StringIO 
import sys 
old_out = sys.stdout # Store stdout to a temp 
result = StringIO() # Will capture standard output as string 
sys.stdout = result # assign result to sys.stdout 
args = [1, 2, 3, 4] 
kwargs = {'sep':'<='} 
print (*args, **kwargs) # This will be written to result, Not displayed in stdout 
sys.stdout = old_out # restore stdout to make things normal 
res = result.getvalue() 
print ("result: {}, length: {}".format(res, len(res))) 

stdout을 복원 할 때까지 표준 출력으로 보내지는 모든 것이 결과 변수에 캡처됩니다.

관련 문제