9
votes

i can silence and restore sys.stdout this way:

import sys
sys.stdout = None
print('hello')  # does not write to stdout
sys.stdout = sys.__stdout__
print('hello')  # writes to stdout

i know i'd better be using contextlib.redirect_stdout which probably does something similar but my question is: why does the above code work?

i'd have assumed python would call things like sys.stdout.write() so whatever i replace sys.stdout with should have a write method (like e.g. io.StringIO) at least.

1
The footnote in docs says they can be None in some conditions: Under some conditions stdin, stdout and stderr as well as the original values __stdin__, __stdout__ and __stderr__ can be None. - Ashwini Chaudhary
I think this is the footnote @AshwiniChaudhary may be referring to. - unutbu
ok, i missed the footnote. thanks! - hiro protagonist

1 Answers

13
votes

print has an explicit check for None.

    /* sys.stdout may be None when FILE* stdout isn't connected */
    if (file == Py_None)
        Py_RETURN_NONE;