有没有办法在 Windows 中停止 time.sleep? [英] Is there a way to stop time.sleep in windows?

查看:49
本文介绍了有没有办法在 Windows 中停止 time.sleep?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 *nix python 信号允许我在它准备好之前停止睡眠.windows下有没有类似的机制——好像所有的方法都是在sleep之后才拦截代码的?

In *nix python signaling allows me to stop sleep before it is ready. Is there any similar mechanism available in windows -- seems that all the methods end up intercepting code only after the sleep?

代码示例:

from time import sleep
.. do something that will intercept the sleep
try:
    sleep(60)
finally:
    print 'how to get here under 60 seconds in windows?'

windows 没有答案的类似问题:中断/中断 python 中的 time.sleep()

Similar question that doesn't have an answer for windows: break/interrupt a time.sleep() in python

推荐答案

signal 的 Python 文档说:

The Python documentation for signal says:

• 尽管 Python 信号处理程序是异步调用的对于 Python 用户而言,它们只能发生在原子"之间Python解释器的说明.这意味着信号在完全用 C 实现的长时间计算中到达(例如大量文本上的正则表达式匹配)可能会延迟任意时间.

• Although Python signal handlers are called asynchronously as far as the Python user is concerned, they can only occur between the "atomic" instructions of the Python interpreter. This means that signals arriving during long calculations implemented purely in C (such as regular expression matches on large bodies of text) may be delayed for an arbitrary amount of time.

time 说:

实际暂停时间可能比要求的要少,因为任何执行该信号后,捕获的信号将终止 sleep()信号的捕捉例程.

The actual suspension time may be less than that requested because any caught signal will terminate the sleep() following execution of that signal’s catching routine.

在 Windows 上,显然 time.sleep() 没有按照文档实现,因为在睡眠期间接收到的信号的处理程序在睡眠的整个持续时间结束之前不会被执行.下面的例子:

On Windows, apparently time.sleep() is not implemented in accordance with the documentation, because the handler for a signal received during sleep is not acted upon until the full duration of the sleep is finished. The following example:

import signal, time

def handler(signum, frame):
    print('Signal handler called with signal', signum)

signal.signal(signal.SIGINT, handler)

print("signal set, sleeping")
time.sleep(10)
print("sleep done")

印刷品:

signal set, sleeping
Signal handler called with signal 2
sleep done

第一行立即发生,第二行在 10 秒后发生,无论中断何时发生.

with the first line occurring immediately and the second two after 10 seconds, regardless of when the interrupt occurs.

正如 Thomas K 所建议的,更好的策略是使用线程和同步.

As Thomas K suggests, a better strategy would be to use threads and synchronization.

这篇关于有没有办法在 Windows 中停止 time.sleep?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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