>  기사  >  백엔드 개발  >  Python 스크립트에서 표준 출력을 캡처하는 방법은 무엇입니까?

Python 스크립트에서 표준 출력을 캡처하는 방법은 무엇입니까?

Patricia Arquette
Patricia Arquette원래의
2024-10-17 14:57:02919검색

How to Capture Standard Output in Python Scripts?

스크립트 표준 출력 캡처

스크립트가 표준 출력에 데이터를 쓰고 해당 출력을 캡처하는 등 특정 작업을 수행하는 시나리오에서 추가 처리에 중요할 수 있습니다. 일반적인 접근 방식은 다음 예에 설명된 것처럼 출력을 변수에 저장하는 것입니다.

<code class="python"># writer.py
import sys

def write():
    sys.stdout.write("foobar")</code>
<code class="python"># mymodule.py
from writer import write

out = write()
print(out.upper())</code>

그러나 이 접근 방식은 스크립트의 출력을 캡처하지 못합니다. StringIO 개체 및 환경 설정을 사용하는 대체 솔루션은 출력을 성공적으로 캡처합니다.

<code class="python">import sys
from cStringIO import StringIO

# setup the environment
backup = sys.stdout

# ####
sys.stdout = StringIO()     # capture output
write()
out = sys.stdout.getvalue() # release output
# ####

sys.stdout.close()  # close the stream
sys.stdout = backup # restore original stdout

print(out.upper())   # post processing</code>

Python 3.4 솔루션

Python 버전 3.4 이상의 경우 contextlib.redirect_stdout 컨텍스트 관리자를 사용하면 간단한 접근 방식을 사용할 수 있습니다.

<code class="python">from contextlib import redirect_stdout
from io import StringIO

f = StringIO()
with redirect_stdout(f):
    help(pow)
s = f.getvalue()</code>

위 내용은 Python 스크립트에서 표준 출력을 캡처하는 방법은 무엇입니까?의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.