2

As the title says, I wanna create a real-time countdown timer in python

So far, I have tried this

import time
def countdown(t):
    print('Countdown : {}s'.format(t))
    time.sleep(t)

But this let the app sleep for the 't' seconds but the seconds in the line don't update themselves

countdown(10)

Desired Output :

Duration : 10s

After 1 second, it should be

Duration : 9s

Yeah, the problem is the previous line Duration : 10s which I have to erase. Is there any way to do this?

dunstorm
  • 372
  • 6
  • 13

2 Answers2

2

Simply do this:

import time
import sys

def countdown(t):
    while t > 0:
        sys.stdout.write('\rDuration : {}s'.format(t))
        t -= 1
        sys.stdout.flush()
        time.sleep(1)

countdown(10)

Import sys and use the sys.stdout.write instead of print and flush() the output before printing the next output.

Note: Use carriage return,"\r" before the string instead of adding a newline.

Taufiq Rahman
  • 5,600
  • 2
  • 36
  • 44
  • When using a number 10 or higher, a trailing zero remains once the counter reaches number 9 and below. For example, `countdown(11)` will look like this: 11 --> 10 --> 90 --> 80 --> 70 --> etc. – howdoicode Aug 19 '20 at 20:11
1

I got a lot of help from this thread : remove last STDOUT line in Python

import time

def countdown(t):
    real = t
    while t > 0:
        CURSOR_UP = '\033[F'
        ERASE_LINE = '\033[K'
        if t == real:
            print(ERASE_LINE + 'Duration : {}s'.format(t))
        else:
            print(CURSOR_UP + ERASE_LINE + 'Duration : {}s'.format(t))
        time.sleep(1)
        t -= 1

countdown(4)
Community
  • 1
  • 1
dunstorm
  • 372
  • 6
  • 13