Display a countdown for the python sleep function

user1681664 picture user1681664 · Jun 20, 2013 · Viewed 40.6k times · Source

I am using time.sleep(10) in my program. Can display the countdown in the shell when I run my program?

>>>run_my_program()
tasks done, now sleeping for 10 seconds

and then I want it to do 10,9,8,7....

is this possible?

Answer

aestrivex picture aestrivex · Jun 20, 2013

you could always do

#do some stuff
print 'tasks done, now sleeping for 10 seconds'
for i in xrange(10,0,-1):
    time.sleep(1)
    print i

This snippet has the slightly annoying feature that each number gets printed out on a newline. To avoid this, you can

import sys
import time
for i in xrange(10,0,-1):
    sys.stdout.write(str(i)+' ')
    sys.stdout.flush()
    time.sleep(1)