Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python print function in real time

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?

like image 537
Rishi Avatar asked Sep 18 '11 19:09

Rishi


1 Answers

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.

like image 83
Oleg Pavliv Avatar answered Sep 22 '22 16:09

Oleg Pavliv