I'm trying to make countdown program with python. I want to turn that into it removes last printed line, so i can print new second.
import time
def countdown():
minute = 60
while minute >= 0:
m, s = divmod(minute, 60)
time_left = str(m).zfill(2) + ':' + str(s).zfill(2)
print(time_left)
time.sleep(1)
minute -= 1
countdown()
I am running python 2.7.13 on Raspberry Pi.
You could write directly to stdout
, instead of using print. And the \\r
character will go to the beginning of the line, not the next line.
import time
import sys
def countdown():
minute = 60
while minute >= 0:
m, s = divmod(minute, 60)
time_left = str(m).zfill(2) + ':' + str(s).zfill(2)
sys.stdout.write("%s\r" % time_left)
sys.stdout.flush()
time.sleep(1)
minute -= 1
Try the following (it's made in python2):
import time, sys
def countdown(totalTime):
try:
while totalTime >= 0:
mins, secs = divmod(totalTime, 60)
sys.stdout.write("\rWaiting for {:02d}:{:02d} minutes...".format(mins, secs))
sys.stdout.flush()
time.sleep(1)
totalTime -= 1
if totalTime <= -1:
print "\n"
break
except KeyboardInterrupt:
exit("\n^C Detected!\nExiting...")
Call it like this: countdown( time ) For example: countdown(600) for 10 minutes.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.