How to flush output of print function?

Walter Nissen picture Walter Nissen · Oct 23, 2008 · Viewed 855.1k times · Source

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.

Answer

CesarB picture CesarB · Oct 23, 2008

On Python 3, print can take an optional flush argument

print("Hello world!", flush=True)

On Python 2 you'll have to do

import sys
sys.stdout.flush()

after calling print. By default, print prints to sys.stdout (see the documentation for more about file objects).