Python中的实时倒计时计时器



如标题所述,我想在python中创建一个实时倒数计时器

到目前为止,我尝试了这个

import time
def countdown(t):
    print('Countdown : {}s'.format(t))
    time.sleep(t)

但这让应用程序在" t"秒内睡觉,但是行中的几秒钟不会自行更新

countdown(10)

所需的输出:

Duration : 10s

1秒钟后,应该是

Duration : 9s

是的,问题是我必须删除的先前行Duration : 10s。有什么方法可以做到吗?

简单地做到这一点:

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)

导入sys并使用sys.stdout.write代替打印和冲洗()在下一个输出之前打印之前的输出。

注意:使用马车返回," r"在字符串之前而不是添加newline。

我从此线程中获得了很多帮助:删除python中的最后一个stdout行

import time
def countdown(t):
    real = t
    while t > 0:
        CURSOR_UP = '33[F'
        ERASE_LINE = '33[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)

最新更新