Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
434 views
in Technique[技术] by (71.8m points)

printing - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...