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
You can do a countdown function like:
import sys
import time
def 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.