Python信号事件终止time.sleep()

时间:2018-10-09 12:21:59

标签: python python-2.7 signals

运行波纹管代码时,为什么time.sleep()会在信号警报到达后立即终止,而不是在单个处理程序完成print signum之后继续运行?

import signal, time


def handler (signum, frame):
    print signum


def main ():
    signal.signal(signal.SIGALRM, handler)
    signal.alarm(2)
    time.sleep(10)
    print "End of main"


if __name__ == "__main__":
    main()

1 个答案:

答案 0 :(得分:1)

sleep()导致调用线程进入睡眠状态,直到经过以秒为单位指定的实时秒数或直到到达一个不可忽略的信号为止。

您可以如下定义自定义睡眠功能:

import datetime
import time
def busy_sleep(seconds):
    start_time = datetime.datetime.now()
    seconds_slept = 0
    while seconds_slept < seconds:
        time.sleep(seconds - seconds_slept)
        seconds_slept = (datetime.datetime.now() - start_time).total_seconds()

只需调用busy_sleep(10)而不是time.sleep(10)