[英]How can I remove last printed line in python?
我正在尝试使用python制作倒计时程序。 我想把它变成它删除最后打印的行,所以我可以打印新的第二行。
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()
我在Raspberry Pi上运行python 2.7.13。
您可以直接写到stdout
,而不用使用print。 \\r
字符将转到行的开头,而不是下一行。
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
尝试以下操作(它是在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...")
这样称呼:countdown( time )例如:countdown(600)10分钟。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.