Python Glossary Русский

Python 3.5+contextlibterm

contextlib.redirect_stderr

redirection

A context manager that temporarily redirects sys.stderr to a file object.

Syntax

with contextlib.redirect_stderr(target): ...

Only Python-level sys.stderr is swapped, so output from C extensions or child processes writing straight to file descriptor 2 slips past it. The change is global and therefore not thread-safe: while the block is active every thread sees the redirect, which makes it a poor fit for library code.

Examples

import contextlib, io, sys
buf = io.StringIO()
with contextlib.redirect_stderr(buf):
    print('err', file=sys.stderr)
print(buf.getvalue().strip())   # → err

See also

Open in the full glossarydocs.python.orgReport an inaccuracy