7

按下 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

同样,我不确定问题出在哪里,但我的终端甚至从不打印我在异常中遇到的两个打印警报。有人可以帮我解决这个问题吗?

4

1 回答 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应该在第二个出现“(再次)”的情况下执行。

于 2011-12-27T15:03:57.413 回答