Search code examples
pythoninfinite-loopkeyboardinterrupttry-exceptsystemexit

python exit infinite while loop with KeyboardInterrupt exception


My while loop does not exit when Ctrl+C is pressed. It seemingly ignores my KeyboardInterrupt exception. The loop portion looks like this:

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

Again, I'm not sure what the problem is but my terminal never even prints the two print alerts I have in my exception. Can someone help me figure this problem out?


Solution

  • Replace your break statement with a raise statement, like below:

    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
    

    The two print statements in the except blocks should execute with '(again)' appearing second.