Reputation: 46869
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.
Upvotes: 10
Views: 1820
Reputation: 280973
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;
Upvotes: 14