python退出带KeyboardInterrupt异常的无限while循环

2024-05-16 23:14:55 发布

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

按下Ctrl+C时,My while循环不退出。它似乎忽略了我的键盘中断异常。循环部分如下所示:

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

再说一次,我不知道问题出在哪里,但我的终端甚至从来没有打印我的两个打印警告,我在我的例外。有人能帮我解决这个问题吗?


Tags: trueifmy键盘eventsprocessmaxnotifier
1条回答
网友
1楼 · 发布于 2024-05-16 23:14:55

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块中的两个print语句时,第二个出现“(again)”。

相关问题 更多 >