python print function in real time

Rishi picture Rishi · Sep 18, 2011 · Viewed 8.5k times · Source

I recently switched OS and am using a newer Python (2.7). On my old system, I used to be able to print instantaneously. For instance, suppose I had a computationally intense for loop:

for i in range(10):
  huge calculation
  print i

then as the code completed each iteration, it would print i

However, on my current system, python seems to cache the stdout so that the terminal is blank for several minutes, after which it prints:

1
2
3

in short succession. Then, after a few more minutes, it prints:

4
5
6

and so on. How can I make python print as soon as it reaches the print statement?

Answer

Oleg Pavliv picture Oleg Pavliv · Sep 18, 2011

Try to call flush of stdout after the print

import sys

...
sys.stdout.flush()

Or use a command line option -u which:

Force stdin, stdout and stderr to be totally unbuffered.