julien2313 julien2313 - 1 month ago 6
Python Question

Why does this timer print just the final result instead of updating every second?

I don't understand why the second part of this code is not printing one number by one in steps of 1 second but all at the end of the script (in this case 3 seconds after the beginning of the second part of the code)?

#!/usr/bin/python2.7

import time

x = 0
maxi = 999999 #I chose a big number to show them scroll

#this part will print all the number on the same line
while x <= maxi:
print '<{}>\r'.format(x),
x+=1
print

#this part will print the numbers with a sleep of 1 second for each print
x = 999998 #I initialized it at this number to only wait 3 seconds
while x <= maxi:
print '<{}>\r'.format(x),
x+=1
time.sleep(1)
print

Answer

That's probably because of buffering. You can try running your program with python -u on the command line, as the man page says

-u Force stdin, stdout and stderr to be totally unbuffered. [...]

Or you can use import sys and put a sys.stdout.flush() just after the print().

If you're wondering why that's needed on the second print and not on the first one, it's most likely because of the sleep. It blocks execution, so nothing is updated / flushed. I think it's actually also happening on the first one but the updates are much more / faster, so you don't notice it.

Comments