我有一个问题,我似乎无法独自解决。我正在编写一个小的python脚本,我想知道为什么我的signal.alarm
在它返回的函数之后仍然有效。这是代码:
class AlarmException(Exception):
pass
def alarmHandler(signum, frame):
raise AlarmException
def startGame():
import signal
signal.signal(signal.SIGALRM, alarmHandler)
signal.alarm(5)
try:
# some code...
return 1
except AlarmException:
# some code...
return -1
def main():
printHeader()
keepPlaying = True
while keepPlaying:
score = 0
for level in range(1):
score += startGame()
answer = raw_input('Would you like to keep playing ? (Y/N)\n')
keepPlaying = answer in ('Y', 'y')
所以问题是当我的startGame()
函数返回时,SIGALRM仍在倒计时并关闭我的程序。这是追溯:
Would you like to keep playing ? (Y/N)
Traceback (most recent call last):
File "game.py", line 84, in <module>
main()
File "game.py", line 80, in main
answer = raw_input('Would you like to keep playing ? (Y/N)\n')
File "game.py", line 7, in alarmHandler
raise AlarmException
__main__.AlarmException
我如何继续说SIGALRM在其所处的功能退出时停止?
谢谢!
答案 0 :(得分:4)
如果要禁用闹钟,请尝试拨打signal.alarm(0)
。
在所有可能情况下,它只是在libc中调用alarm()
,而man alarm
表示alarm(0)
“...使当前警报无效并且信号SIGALRM将不会被传递。”< / p>