python中的高精度倒计时

时间:2018-05-29 08:00:43

标签: python

我需要在python中实现倒数计时器。我尝试了这个,但程序卡住了,我不得不强制退出。出于同样的原因,我不能在run()方法中有一个不定式的循环。我该怎么办?

class th(Thread):
    def __init__(self):
        Thread.__init__(self)

    def run(self):
        printer()

def printer():
    print(time.time()*1000.0)
    time.sleep(1)
    printer()

thread1 = th()
thread1.start()

1 个答案:

答案 0 :(得分:0)

您没有说出您正在使用的操作系统,因此我假设您使用的是具有标准ANSI / VT100终端的系统,因此我们可以使用ANSI转义序列移动光标等。如果您使用的是非标准操作系统,这些序列可能无法在您的终端中使用。

此程序显示自程序启动以来的秒数,位于终端窗口的顶部。时间显示每0.1秒更新一次。在时间显示下面有一个input提示,等待用户关闭程序。

from time import perf_counter
from threading import Timer

# Some ANSI/VT100 Terminal Control Escape Sequences
CSI = '\x1b['
CLEAR = CSI + '2J'
CLEAR_LINE = CSI + '2K'
SAVE_CURSOR = CSI + 's'
UNSAVE_CURSOR = CSI + 'u'
GOTO_LINE = CSI + '%d;0H'

def emit(*args):
    print(*args, sep='', end='', flush=True)

start_time = perf_counter()
def time_since_start():
    return '{:.6f}'.format(perf_counter() - start_time)

def show_time(interval):
    global timer
    emit(SAVE_CURSOR, GOTO_LINE % 1, CLEAR_LINE, time_since_start(), UNSAVE_CURSOR)
    timer = Timer(interval, show_time, (interval,))
    timer.start()

# Set up scrolling, leaving the top line fixed
emit(CLEAR, CSI + '2;r', GOTO_LINE % 2)

# Start the timer loop
show_time(interval=0.1)

input('Press Enter to stop the timer:')
timer.cancel()

# Cancel scrolling
emit('\n', SAVE_CURSOR, CSI + '0;0r', UNSAVE_CURSOR)

此代码源自this previous answer of mine

这是一个更原始的版本,没有光标控制,除了使用'\r'回车控制字符,它应该适用于任何系统。根据您的终端,您可能不需要flush=True arg到print

from time import time as perf_counter
from threading import Timer

start_time = perf_counter()

def show_time(interval):
    global timer
    print('  {:.6f}'.format(perf_counter() - start_time), end='\r', flush=True)
    timer = Timer(interval, show_time, (interval,))
    timer.start()

# Start the timer loop
show_time(interval=0.1)

input(15 * ' ' + ': Press Enter to stop the timer.\r')
timer.cancel()
相关问题