Reputation: 392
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?
Upvotes: 2
Views: 6198
Reputation: 5704
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.
Upvotes: 3
Reputation: 392
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)
Upvotes: 1