Base di conoscenzaCentro esami
ITItaliano
Scegli la lingua13

CKTIS / Python

contextlib.redirect_stderr

Collega temporaneamente sys.stderr a un flusso scrivibile e lo fornisce con as.

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

Sintassi

with contextlib.redirect_stderr(new_target) as stream:

Collega temporaneamente sys.stderr a un flusso scrivibile e lo fornisce con as.

I thread dello stesso interprete condividono sys.stderr. La rientranza non garantisce sicurezza tra thread. Qui print indirizzato a sys.stderr salva notice nel buffer senza cambiare sys.stdout. L’uscita ripristina il flusso precedente anche dopo un errore.

Il cambiamento è globale e annidabile e non reindirizza il canale di errore di sistema di un sottoprocesso.

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

Esempi

import contextlib
import io, sys

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

Risultato

notice

Il cambiamento è globale e annidabile e non reindirizza il canale di errore di sistema di un sottoprocesso.

Fonti