I'm running python version 2.7.3 on MacOSX.
Consider this block of code:
from __future__ import print_function
import time
x = 0
while x < 5:
print(x)
x += 1
time.sleep(1)
If I run this script, I observe the output I expect: The numbers 0
through 4
with a \n
character appended to each number. Futhermore, each number displays after a one second pause.
0
1
2
3
4
Now consider this code block:
from __future__ import print_function
import time
x = 0
while x < 5:
print(x, end='')
x += 1
time.sleep(1)
The output is what I expect, 01234
without the \n
's, but the timing is unexpected. Rather than displaying each digit after a one-second pause, the process waits four seconds, then displays all five numbers.
Why does print('string')
behave differently from print('string', end='')
in while-loops? Is there any way to display the characters without newlines, one second at a time? I tried sys.stdout.write(str(x))
, but it behaves the same way as print(end='')
.