Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Display a countdown for the python sleep function

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?

like image 774
user1681664 Avatar asked Jun 20 '13 17:06

user1681664


People also ask

How do you use the sleep function in Python?

If you've got a Python program and you want to make it wait, you can use a simple function like this one: time. sleep(x) where x is the number of seconds that you want your program to wait.

How does the countdown function work in Python?

Countdown time in PythonThe divmod() method takes two numbers and returns a pair of numbers (a tuple) consisting of their quotient and remainder. end='\r' overwrites the output for each iteration. The value of time_sec is decremented at the end of each iteration.


2 Answers

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) 
like image 199
aestrivex Avatar answered Sep 22 '22 02:09

aestrivex


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.

like image 45
Barkles Avatar answered Sep 22 '22 02:09

Barkles