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.
stdout. A built-in file object that is analogous to the interpreter's standard output stream in Python. stdout is used to display output directly to the screen console.
Python print() function prints the message to the screen or any other standard output device. In the print() function, it requires an empty parenthesis at the end that tells Python to execute the function rather than calling it by name.
In IDLE, sys. __stdout__ is the program's original standard output - which goes nowhere, since it's not a console application. In other words, IDLE itself has already replaced sys. stdout with something else (its own console window), so you're taking two steps backwards by replacing your own stdout with __stdout__ .
print() and Standard Out. Every running program has a text output area called "standard out", or sometimes just "stdout". The Python print() function takes in python data such as ints and strings, and prints those values to standard out.
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With