Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Python

contextlib.redirect_stdout

Temporarily replaces the Python standard output stream so printed text can be captured.

Version: Python 3.14; repository image, production runtime not attested

Syntax

with contextlib.redirect_stdout(new_target) as stream:

Temporarily replaces the Python standard output stream so printed text can be captured.

Exiting restores the previous stream. This process-wide replacement does not automatically capture subprocess output.

Capture output from Python calls such as print by temporarily replacing sys.stdout. The target must accept writes; nested scopes restore their respective prior streams on exit. It changes global state for threads sharing the interpreter, not subprocess file descriptors. Here the captured text includes the slash separator and the final newline.

import io, sys
from contextlib import redirect_stdout
a, b = io.StringIO(), io.StringIO()
old = sys.stdout
with redirect_stdout(a):
    print("A")
    with redirect_stdout(b):
        print("B")
    print("C")
assert sys.stdout is old
assert a.getvalue() == "A\nC\n" and b.getvalue() == "B\n"

Examples

import contextlib
from io import StringIO

text = StringIO()
with contextlib.redirect_stdout(text):
    print(3, 5, sep="/")
print(repr(text.getvalue()))

Result

'3/5\n'

Capture output from Python calls such as print by temporarily replacing sys.stdout. The target must accept writes; nested scopes restore their respective prior streams on exit. It changes global state for threads sharing the interpreter, not subprocess file descriptors. Here the captured text includes the slash separator and the final newline.

Sources