Display a countdown for the python sleep function Display a countdown for the python sleep function python python

Display a countdown for the python sleep function


you could always do

#do some stuffprint '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 sysimport timefor i in xrange(10,0,-1):    sys.stdout.write(str(i)+' ')    sys.stdout.flush()    time.sleep(1)


This is the best way to display a timer in the console for Python 3.x:

import timeimport sysfor remaining in range(10, 0, -1):    sys.stdout.write("\r")    sys.stdout.write("{:2d} seconds remaining.".format(remaining))    sys.stdout.flush()    time.sleep(1)sys.stdout.write("\rComplete!            \n")

This writes over the previous line on each cycle.


You can do a countdown function like:

import sysimport timedef countdown(t, step=1, msg='sleeping'):  # in seconds    pad_str = ' ' * len('%d' % step)    for i in range(t, 0, -step):        print '%s for the next %d seconds %s\r' % (msg, i, pad_str),        sys.stdout.flush()        time.sleep(step)    print 'Done %s for %d seconds!  %s' % (msg, t, pad_str)

The carriage return \r and the comma , will keep the print in the same line (avoiding one line for each countdown value)

As the number of seconds decreases, the pad_str will ensure the last line is overwritten with spaces instead of leaving the last character(s) behind as the output shortens.

The final print overwrites the last status message with a done message and increments the output line, so there is evidence of the delay.