How do I force Python's print function to output to the screen?
This is not a duplicate of Disable output buffering - the linked question is attempting unbuffered output, while this is more general. The top answers in that question are too powerful or involved for this one (they're not good answers for this), and this question can be found on Google by a relative newbie.
In Python 3 you can overwrite print function with default set to
flush = True
Using the
-u
command-line switch works, but it is a little bit clumsy. It would mean that the program would potentially behave incorrectly if the user invoked the script without the-u
option. I usually use a customstdout
, like this:... Now all your
print
calls (which usesys.stdout
implicitly), will be automaticallyflush
ed.Since Python 3.3, you can force the normal
print()
function to flush without the need to usesys.stdout.flush()
; just set the "flush" keyword argument to true. From the documentation:Dan's idea doesn't quite work:
The result:
I believe the problem is that it inherits from the file class, which actually isn't necessary. According to the docs for sys.stdout:
so changing
to
makes it work just fine.
Print by default prints to
sys.stdout
.References: