Skip to content Skip to sidebar Skip to footer

Real Time Countdown Timer In Python

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

Solution 1:

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.

Solution 2:

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

import time

defcountdown(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)

Post a Comment for "Real Time Countdown Timer In Python"