contextlib.redirect_stderr
Prev: contextlib.nullcontext | Up: contextlib | Next: contextlib.redirect_stdout
Rel: contextlib.AbstractAsyncContextManager, contextlib.AbstractContextManager, contextlib.aclosing, contextlib.asynccontextmanager
Ref: docs.python.org — contextlib.redirect_stderr
Tags: #public #python3 #stdlib #contextlib
Import
import contextlib
from contextlib import redirect_stderr
Signature & Overview
contextlib.redirect_stderr(new_target)
Context manager for temporarily redirecting stderr to another file.
Usage
from contextlib import redirect_stderr
import io
import sys
buf = io.StringIO()
with redirect_stderr(buf):
print("warn!", file=sys.stderr)
assert buf.getvalue().strip() == "warn!"
Gotchas
- Process-global (
sys.stderr) and NOT thread-safe: Redirects stderr for all threads in the process; great for CLI tests, unsafe in concurrent servers. - Python-level only: Does not capture output written directly to OS file descriptor 2 by C extensions or subprocesses.
REPL Inspect
from contextlib import redirect_stderr
help(redirect_stderr)
Linked from
Related notes
- tuts/python3/stdlib_module/contextlib/nullcontext Linked here; links to this page; shared tags: #contextlib, #stdlib
- tuts/python3/stdlib_module/contextlib/redirect_stdout 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