Python `print` does not work in a loop

I have several cycles together and sleep in the innermost cycle. eg:

from time import sleep for i in range(10): print i, for j in range(-5,5): if j > 0: print '.', else: print 'D', sleep(1) print '' 

if you run the code, you can expect i get after D sleep 1 second and another D and again sleeping until the end.

but the result will be different, it waits 10 seconds and prints the whole line 0 DDDDDD . . . . 0 DDDDDD . . . . and again waiting to print the next line.

I found that the comma at the end of the print is causing this problem. How can I solve it?

+7
python
source share
2 answers

Due to the existence of a comma, output buffers up to \n .

You must clear stdout after every print, or use sys.stdout.write and sys.stdout.write buffer.

Determine the printing method:

 import sys def my_print(text): sys.stdout.write(str(text)) sys.stdout.flush() 

and at the end of the line type \n

+12
source share

The problem with using print <something>, buffered and printed only when the result identifier is ready to print. A.

You can solve it with print_function from __future__ (which will also match Python 3):

 from __future__ import print_function from time import sleep import sys for i in range(10): print(i, end='') for j in range(-5,5): if j > 0: print('.', end='') else: print('D', end='') sys.stdout.flush() sleep(1) print('') 
+1
source share

All Articles