gpt4 book ai didi

python退出无限while循环并出现KeyboardInterrupt异常

转载 作者:太空狗 更新时间:2023-10-30 00:33:31 28 4
gpt4 key购买 nike

当按下 Ctrl+C 时,我的 while 循环不会退出。它似乎忽略了我的 KeyboardInterrupt 异常。循环部分如下所示:

while True:
try:
if subprocess_cnt <= max_subprocess:
try:
notifier.process_events()
if notifier.check_events():
notifier.read_events()
except KeyboardInterrupt:
notifier.stop()
break
else:
pass
except (KeyboardInterrupt, SystemExit):
print '\nkeyboardinterrupt found!'
print '\n...Program Stopped Manually!'
raise

同样,我不确定问题出在哪里,但我的终端甚至从未打印出异常中的两个打印警报。谁能帮我解决这个问题?

最佳答案

break 语句替换为 raise 语句,如下所示:

while True:
try:
if subprocess_cnt <= max_subprocess:
try:
notifier.process_events()
if notifier.check_events():
notifier.read_events()
except KeyboardInterrupt:
notifier.stop()
print 'KeyboardInterrupt caught'
raise # the exception is re-raised to be caught by the outer try block
else:
pass
except (KeyboardInterrupt, SystemExit):
print '\nkeyboardinterrupt caught (again)'
print '\n...Program Stopped Manually!'
raise

except block 中的两个打印语句应该以“(再次)”出现在第二个位置执行。

关于python退出无限while循环并出现KeyboardInterrupt异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8645632/

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