如何删除 python 中最后打印的行?

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

我是 运行 python 2.7.13 Raspberry Pi。

您可以直接写入 stdout,而不是使用打印。 \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...")

这样称呼它: 倒计时(时间) 例如:倒计时(600)10分钟。