Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why does sys.stdout = None work?

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.

like image 920
hiro protagonist Avatar asked Apr 10 '18 15:04

hiro protagonist


People also ask

What is SYS stdout?

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.

How to print Standard output in Python?

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.

What is SYS __ stdout __?

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__ .

Does print in Python go to 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.


1 Answers

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;
like image 152
user2357112 supports Monica Avatar answered Oct 23 '22 14:10

user2357112 supports Monica