Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Python

contextlib.redirect_stderr

Temporarily routes writes to the Python standard error stream into a replacement stream.

Version: Python 3.14; repository image, production runtime not attested

Syntax

with contextlib.redirect_stderr(new_target) as stream:

Temporarily routes writes to the Python standard error stream into a replacement stream.

Standard output is a separate stream. Redirection changes interpreter-wide state and should be scoped narrowly.

Temporarily rebind sys.stderr to a writable target and return the target at entry. This catches Python-level diagnostics that consult sys.stderr, including the explicit print in the sample. The old stream returns on exit even after an error. Its binding is interpreter-wide and reentrant, and does not redirect a subprocess's operating-system error stream. Threads of one interpreter share sys.stderr. Reentrancy does not provide thread safety.

import io, sys
from contextlib import redirect_stderr
before = sys.stderr
s = io.StringIO()
try:
    with redirect_stderr(s) as stream:
        assert stream is s
        print("warning", file=sys.stderr)
        raise ValueError
except ValueError:
    assert sys.stderr is before and s.getvalue() == "warning\n"
other = io.StringIO()
with redirect_stderr(s):
    with redirect_stderr(other):
        assert sys.stderr is other
    assert sys.stderr is s

Examples

import contextlib
import io, sys

buffer = io.StringIO()
with contextlib.redirect_stderr(buffer):
    print("notice", file=sys.stderr)
print(buffer.getvalue().strip())

Result

notice

Temporarily rebind sys.stderr to a writable target and return the target at entry. This catches Python-level diagnostics that consult sys.stderr, including the explicit print in the sample. The old stream returns on exit even after an error. Its binding is interpreter-wide and reentrant, and does not redirect a subprocess's operating-system error stream. Threads of one interpreter share sys.stderr. Reentrancy does not provide thread safety.

Sources