Python 2.7 carriage return countdown

Kvass picture Kvass · Jul 2, 2013 · Viewed 7.5k times · Source

I'm having trouble implementing a simple countdown in python using a carriage return. I have two versions, each with problems.

Print Version:

for i in range(10):
    print "\rCountdown: %d" % i
    time.sleep(1)

Problem: The \r doesn't do anything because a newline is printed at the end, so it gives the output:

Countdown: 0
Countdown: 1
Countdown: 2
Countdown: 3
Countdown: 4
Countdown: 5
Countdown: 6
Countdown: 7
Countdown: 8
Countdown: 9

Sys.stdout.write Version:

for i in range(10):
    sys.stdout.write("\rCountdown: %d" % i)
    time.sleep(1)
print "\n"

Problem: All the sleep happens at the beginning, and after 10 seconds of sleep it just prints Countdown: 9 to the screen. I can see the \r is working behind the scenes, but how do I get the prints to be interspersed in the sleep?

Answer

Brian picture Brian · Jul 3, 2013

For solution number 2, you need to flush stdout.

for i in range(10):
    sys.stdout.write("\rCountdown: %d" % i)
    sys.stdout.flush()
    time.sleep(1)
print ''

Also, just print an empty string since print will append the newline. Or use print '\n' , if you think it is more readable as the trailing comma suppresses the newline that would typically be appended.

Not sure how to fix the first one though...