22

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?

user1681664
  • 1,533
  • 8
  • 23
  • 50

8 Answers8

34

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)
David Resnick
  • 4,560
  • 4
  • 36
  • 41
aestrivex
  • 4,640
  • 1
  • 23
  • 41
16

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

import time
import sys

for 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.

Barkles
  • 503
  • 6
  • 12
7

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.

Maruf
  • 712
  • 9
  • 36
Saullo G. P. Castro
  • 49,101
  • 22
  • 160
  • 223
  • To prevent a new line inserted every second in the countdown, the statement `print '%s for the next %d seconds %s\r' % (msg, i, pad_str),` should be changed to `sys.stdout.write( '%s for the next %d seconds %s\r' % (msg, i, pad_str),)`. – Jack Fleeting Feb 24 '19 at 23:47
2

Here's one I did:

import time
a = input("How long is the countdown?")
while a != 0:
    print a
    time.sleep(1)
    a = a-1

At the end if you and an else you can put an alarm or whatever.

Community
  • 1
  • 1
2

This is something that I've learned at one of my first python lessons, we played with ["/","-","|","\","|"] but the principle is the same:

import time

for i in reversed(range(0, 10)):
    time.sleep(1)
    print "%s\r" %i,
Azur
  • 53
  • 4
1

Sure, just write a loop that prints 10 minus the iteration counter, then have it sleep 1 second each iteration and run for 10 iterations. Or, to be even more flexible:

def printer(v):
    print v
def countdown_timer(duration, step=1, output_function=printer,
                    prompt='Waiting {duration} seconds.'):
    output_function(prompt.format(duration=duration))
    for i in xrange(duration/step):
        output_function(duration - step * i)
Silas Ray
  • 24,298
  • 5
  • 44
  • 60
1

time.sleep() may return earlier if the sleep is interrupted by a signal or later (depends on the scheduling of other processes/threads by OS/the interpreter).

To improve accuracy over multiple iterations, to avoid drift for large number of iterations, the countdown may be locked with the clock:

#!/usr/bin/env python
import sys
import time

for i in reversed(range(1, 1001)):
    time.sleep(1 - time.time() % 1) # sleep until a whole second boundary
    sys.stderr.write('\r%4d' % i)
jfs
  • 346,887
  • 152
  • 868
  • 1,518
1

A simple solution that clears the last number from the console.

import time

for i in range(10,0,-1):
    print(f"{i}", end="\r", flush=True)
    time.sleep(1)

By default, the print function sets end="\n" which means subsequent calls to print will be printed on a new line. You can change this to end=“\r” to replace the output after each call (https://www.codespeedy.com/how-does-carriage-return-work-in-python/).

Also, using flush means you don't have to worry about buffering issues (What does print()'s `flush` do?).

This is how it looks:

countdown

zcahgg1
  • 15
  • 7