【问题标题】:How can I remove last printed line in python?如何删除python中的最后一个打印行?
【发布时间】:2018-10-17 17:01:30
【问题描述】:

我正在尝试用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。

【问题讨论】:

标签: python python-2.7 time countdown


【解决方案1】:

您可以直接写信给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

【讨论】:

    【解决方案2】:

    试试下面的(它是用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(600) 10 分钟。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-03-18
      • 1970-01-01
      • 1970-01-01
      • 2022-08-13
      • 1970-01-01
      相关资源
      最近更新 更多