CKTIS / Python
contextlib.redirect_stderr
Relie temporairement sys.stderr à un flux accessible en écriture et le fournit par as.
Version : Python 3.14; repository image, production runtime not attested
Syntaxe
with contextlib.redirect_stderr(new_target) as stream:Relie temporairement sys.stderr à un flux accessible en écriture et le fournit par as.
Les fils du même interpréteur partagent sys.stderr. La réentrance ne garantit pas la sûreté entre fils. Ici print vise explicitement sys.stderr et notice arrive dans le tampon, sans changer sys.stdout. La sortie rétablit l’ancien flux même après erreur.
Le changement est global et imbriquable et ne redirige pas le canal d’erreur système d’un sous-processus.
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
Exemples
import contextlib
import io, sys
buffer = io.StringIO()
with contextlib.redirect_stderr(buffer):
print("notice", file=sys.stderr)
print(buffer.getvalue().strip())
Résultat
notice
Le changement est global et imbriquable et ne redirige pas le canal d’erreur système d’un sous-processus.