中断信号唤醒 Python 进程从休眠状态并从中断处继续?

Interrupt signals awake Python process from sleeping and continue where it left off?

下面的代码会每5秒打印一次当前时间,它用int_handler处理键盘中断信号。

from signal import *
import time
from datetime import datetime


def int_handler(*args):
    print 'interrupted'

signal(SIGINT, int_handler)

while True:
    print datetime.now()
    time.sleep(5)

但是我每次按Ctrl-C都会马上打印出当前时间,然后继续运行 .

2016-06-28 18:17:19.441574
2016-06-28 18:17:24.446659
2016-06-28 18:17:29.451759
2016-06-28 18:17:34.452328
^Cinterrupted
2016-06-28 18:17:37.244227
^Cinterrupted
2016-06-28 18:17:37.692217
^Cinterrupted
2016-06-28 18:17:38.236343
^Cinterrupted
2016-06-28 18:17:38.572194
2016-06-28 18:17:43.577122
2016-06-28 18:17:48.577242

好像是中断把进程从休眠中唤醒,处理程序被执行,不知何故又回到了while循环。

谁能给我解释一下这是为什么?谢谢!

来自 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.

https://docs.python.org/3/library/time.html#time.sleep

所以你所描述的正是正在发生的事情:在你的信号处理程序中处理信号之后,执行在睡眠之后继续,这是你的 while 循环中的最后一个表达式。

因此,为了真正睡大约 5 秒而忽略打扰,您必须在睡觉前存储时间并检查醒来时是否已经足够,或者再睡一会儿。