相关疑难解决方法(0)

在python中中断/中断time.sleep()

我需要使用ctrl c从time.sleep()中断.

While 1:
    time.sleep(60)
Run Code Online (Sandbox Code Playgroud)

在上面的代码中,当控件进入time.sleep函数时,需要经过整整60秒才能处理CTRL C

有没有优雅的方式来做到这一点.这样我即使在控制时间内也可以中断.睡眠功能

编辑

我在一个遗留实现上测试它,在Windows 2000上使用python 2.2导致了所有的麻烦.如果我使用了更高版本的python CTRL C会中断sleep().我通过在for循环中调用sleep(1)来快速破解.这暂时解决了我的问题

python

46
推荐指数
3
解决办法
5万
查看次数

Python中的abortable sleep()

我需要一种sleep()可以中止的方法(如此此处所述).

我的方法是threading.Event.wait()在指定的持续时间内超时:

def abortable_sleep(secs, abort_event):
    abort_event.wait(timeout=secs)
    abort_event.clear()
Run Code Online (Sandbox Code Playgroud)

在调用之后abortable_sleep(10, _abort)我现在可以(从另一个线程)调用_event.set(_abort)让它abortable_sleep()在10秒之前终止.

例:

def sleeping_thread():
    _start = time.perf_counter()
    print("%f thread started" % (time.perf_counter() - _start))
    abortable_sleep(5, _abort)
    print("%f thread stopped" % (time.perf_counter() - _start))

if __name__ == '__main__':

    _abort = threading.Event()
    while True:
        threading.Thread(target=sleeping_thread).start()
        time.sleep(3)
        _abort.set()
        time.sleep(1)
Run Code Online (Sandbox Code Playgroud)

输出:

0.000001 thread started
3.002668 thread stopped
0.000002 thread started
3.003014 thread stopped
0.000001 thread started
3.002928 thread stopped
0.000001 thread started …
Run Code Online (Sandbox Code Playgroud)

python thread-sleep

8
推荐指数
1
解决办法
2128
查看次数

标签 统计

python ×2

thread-sleep ×1