Python 3.4+contextlibterm
contextlib.redirect_stdout
redirection
A context manager that temporarily redirects sys.stdout to a file object.
Syntax
with contextlib.redirect_stdout(target): ...
The swap is global: while the with block is active, sys.stdout is redirected for the whole program, other threads included — which is why this is a poor fit for library code and threaded applications. Output from subprocesses or from C code writing straight to file descriptor 1 is unaffected; only writes going through sys.stdout are captured. There is a matching redirect_stderr, and the usual use case is tests or capturing output from someone else's function that prints instead of returning.
Examples
import contextlib, io
buf = io.StringIO()
with contextlib.redirect_stdout(buf):
print('hi')
print(buf.getvalue().strip()) # → hi
See also
Open in the full glossarydocs.python.orgReport an inaccuracy