PyDocs

Nav

Python Runtime Services

redirect_stdout

contextlib

function · Added in 3.4 (source)
  • redirect_stdout(new_target)
Context manager for temporarily redirecting stdout to another file.

# How to send help() to stderr
with redirect_stdout(sys.stderr):
    help(dir)

# How to write help() to a file
with open('help.txt', 'w') as f:
    with redirect_stdout(f):
        help(pow)
1 Example
>>> from contextlib import redirect_stdout
>>> from io import StringIO
>>> stream = StringIO()
>>> write_to_stream = redirect_stdout(stream)
>>> with write_to_stream:
...     print("This is written to the stream rather than stdout")
...     with write_to_stream:
...         print("This is also written to the stream")
...
>>> print("This is written directly to stdout")
This is written directly to stdout
>>> print(stream.getvalue())
This is written to the stream rather than stdout
This is also written to the stream
from the Python docs
See Also
No see-alsos for contextlib/redirect_stdout
0 Notes
No notes for redirect_stdout