python中的高精度倒计时
我需要用python实现一个倒计时。我试过了,但是程序卡住了,我不得不被迫退出。出于同样的原因,我不能在run()方法中使用不定式循环。我该怎么办python中的高精度倒计时,python,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)
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()
你没有说你使用的是哪个操作系统,所以我假设你使用的是一个带有标准ANSI/VT100终端的系统,所以我们可以使用ANSI转义序列来移动光标,等等。如果你使用的是非标准操作系统,这些序列可能在你的终端中不起作用
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()
该程序在终端窗口顶部显示自程序启动以来的秒数。时间显示每0.1秒更新一次。在时间显示下方有一个输入
提示,等待用户关闭程序
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)
此代码源于
这里有一个更原始的版本,没有光标控件,除了使用
'\r'
回车控件字符外,它应该适用于任何系统。您可能不需要flush=True
arg来打印
,这取决于您的终端
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()
你能展示完整的代码吗?“程序崩溃”不是一个可接受的问题描述。它是如何崩溃的?你为什么要继承线程?您可以使用线程,而不必让自己的类将递归调用更改为while循环这应该是一个倒计时计时器吗?算了!顺便说一句,不打算用作高精度定时功能。看见