CKTIS / Python
contextlib.redirect_stderr
Vincula temporalmente sys.stderr a un destino escribible y lo entrega mediante as.
Versión: Python 3.14; repository image, production runtime not attested
Sintaxis
with contextlib.redirect_stderr(new_target) as stream:Vincula temporalmente sys.stderr a un destino escribible y lo entrega mediante as.
Los hilos del mismo intérprete comparten sys.stderr. La reentrada no garantiza seguridad entre hilos. Aquí print dirigido a sys.stderr guarda notice en el búfer sin cambiar sys.stdout. La salida restaura el flujo anterior incluso tras un error.
El cambio es global y anidable y no redirige el canal de errores del sistema de un subproceso.
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
Ejemplos
import contextlib
import io, sys
buffer = io.StringIO()
with contextlib.redirect_stderr(buffer):
print("notice", file=sys.stderr)
print(buffer.getvalue().strip())
Resultado
notice
El cambio es global y anidable y no redirige el canal de errores del sistema de un subproceso.