Python 如何通过 KeyboardInterrupt 退出无限 while 循环

7 投票
1 回答
41538 浏览
提问于 2025-04-17 09:05

我的while循环在按下Ctrl+C时没有退出。它似乎忽略了我的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

我还是不太确定问题出在哪里,但我的终端甚至没有打印出我在异常处理里放的两个打印提示。有人能帮我找出这个问题吗?

1 个回答

15

把你的 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 块里的两个打印语句应该会执行,并且 '(again)' 会在第二个打印出来。

撰写回答