contextlib.redirect_stdout
Prev: contextlib.redirect_stderr | Up: contextlib | Next: contextlib.suppress
Rel: contextlib.AbstractAsyncContextManager, contextlib.AbstractContextManager, contextlib.aclosing, contextlib.asynccontextmanager
Ref: docs.python.org — contextlib.redirect_stdout
Tags: #public #python3 #stdlib #contextlib
Import
import contextlib
from contextlib import redirect_stdout
Signature & Overview
contextlib.redirect_stdout(new_target)
Context manager for temporarily redirecting stdout to another file.
Usage
from contextlib import redirect_stdout
import io
buf = io.StringIO()
with redirect_stdout(buf):
print("captured")
assert buf.getvalue().strip() == "captured"
Gotchas
- Process-global (
sys.stdout) and NOT thread-safe: Great for capturingprint()in tests or notebooks, not for multi-threaded web handlers. - Does not redirect C-level fd 1: Subprocesses or C
printf()bypasssys.stdout.
REPL Inspect
from contextlib import redirect_stdout
help(redirect_stdout)
Linked from
Related notes
- tuts/python3/stdlib_module/contextlib/redirect_stderr Linked here; links to this page; shared tags: #contextlib, #stdlib
- tuts/python3/stdlib_module/contextlib/suppress Linked here; links to this page; shared tags: #contextlib, #stdlib
- tuts/python3/stdlib_module/contextlib Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/contextlib/AbstractAsyncContextManager Linked here; shared tags: #contextlib, #stdlib
- tuts/python3/stdlib_module/contextlib/AbstractContextManager Linked here; shared tags: #contextlib, #stdlib
- tuts/python3/stdlib_module/contextlib/aclosing Linked here; shared tags: #contextlib, #stdlib
- tuts/python3/stdlib_module/contextlib/asynccontextmanager Linked here; shared tags: #contextlib, #stdlib
- tuts/python3/stdlib_module/contextlib/AsyncExitStack shared tags: #contextlib, #stdlib
- tuts/python3/stdlib_module/contextlib/chdir shared tags: #contextlib, #stdlib
- tuts/python3/stdlib_module/contextlib/closing shared tags: #contextlib, #stdlib