混淆时间。睡觉在Python“while True”循环中

2024-04-25 08:53:59 发布

您现在位置:Python中文网/ 问答频道 /正文

初级初级 我在ubuntu上使用python2.7版本。 关于python中的一个小代码片段,我有点困惑。我知道在python中while True意味着无限循环。我有以下代码:

#!/usr/bin/env python
import signal
import time

def ctrlc_catcher(signum, frm):
     print "Process can't be killed with ctrl-c!"

def alarm_catcher(signum,frame):
    print "Got an alarm"


signal.signal(signal.SIGINT, ctrlc_catcher)
signal.signal(signal.SIGALRM, alarm_catcher)


while True:
   signal.alarm(1)
   pass

当我执行程序时,输出是空白的,当我按下Ctrl-C键时,它显示“Process can't be…”消息。 我的问题是signal.alarm(1)为什么不工作? 但是如果我用

^{pr2}$

之后,警报被触发,在输出屏幕上,我每秒钟都会看到“收到警报”消息。 是什么时间。睡觉(1) 这样会触发警报吗? 谢谢


Tags: 代码importtruesignaldef警报beprocess
2条回答

问题是你的闹钟写得太多了。以下内容来自^{} docs

signal.alarm(time)

If time is non-zero, this function requests that a SIGALRM signal be sent to the process in time seconds. Any previously scheduled alarm is canceled (only one alarm can be scheduled at any time).

在第一个例子中,你一直在重置警报。你从现在开始设置1秒的警报,然后0.00001秒之后你设置了1秒的警报,然后0.00001秒之后你设置了1秒后的警报。。。所以以后警报总是1秒!在第二个例子中,通过睡眠,你可以在重置警报前留出1秒的时间,这样它实际上有时间去关闭。在

我想你在第一个例子中想写的是

signal.alarm(1)
while True:
    pass

相关问题 更多 >