gpt4 book ai didi

python - 当函数返回时停止 SIGALRM

转载 作者:行者123 更新时间:2023-11-28 21:53:11 27 4
gpt4 key购买 nike

我有一个我自己似乎无法解决的问题。我正在编写一个小的 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 所在的函数退出时,我该如何继续告诉 SIGALRM 停止?

谢谢!

最佳答案

当您想禁用警报时,尝试调用 signal.alarm(0)

很可能它只是调用 libc 中的 alarm(),而 man alarmalarm(0) “...使当前警报无效,信号 SIGALRM 将不会被传送。”

关于python - 当函数返回时停止 SIGALRM,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27013127/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com