中断/中断 python 中的 time.sleep() [英] break/interrupt a time.sleep() in python

查看:77
本文介绍了中断/中断 python 中的 time.sleep()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I need to break from time.sleep() using ctrl c.

While 1:
    time.sleep(60)

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

In the above code when the control enters time.sleep function an entire 60 seconds needs to elapsed for python to handled the CTRL C

有什么优雅的方法可以做到这一点.这样即使控制到了我也可以中断.睡眠功能

Is there any elegant way to do it. such that I can interrupt even when the control is in time.sleep function

编辑

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

I was testing it on a legacy implementation which uses python 2.2 on windows 2000 which caused all the trouble . If I had used a higher version of python CTRL C would have interrupted the sleep() . I did a quick hack by calling sleep(1) inside a for loop . which temporarily fixed my issue

推荐答案

不确定这段代码的含义 - 但如有必要,请使用更短的 sleep() 间隔并在其周围放置一个 for 循环:

Not sure what the sense of this code is - but if necessary use a shorter sleep() interval and put a for loop around it:

for i in range(60):
   sleep(1)

使用 try..except 捕获 KeyboardInterrupt 异常很简单

Catching the KeyboardInterrupt exception using try..except is straight-forward

这篇关于中断/中断 python 中的 time.sleep()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆