ID EN
Contextlib

redirect_stdout

Python 3.11

Context manager for temporarily redirecting sys.stdout to another file or file-like object.

Syntax

PYTHON
contextlib.redirect_stdout(new_target)

Examples

Example 1
PYTHON
with redirect_stdout(io.StringIO()) as f:
    help(pow)
s = f.getvalue()
Example 2
PYTHON
with open('help.txt', 'w') as f:
    with redirect_stdout(f):
        help(pow)
Example 3
PYTHON
with redirect_stdout(sys.stderr):
    help(pow)

See Also

sys.stdout help() io.StringIO with help() help() sys.stdout reentrant