7
votes

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?

1
Your first except KeyboardInterrupt catches the exception. It won't be visible to the second except (KeyboardInterrupt, SystemExit) if you don't re-raise it. - eumiro
@eumiro - I commented out the first KeyboardInterrupt and replaced the contents of the exception with 'pass' but I'm still experiencing the same problem. Ctrl+C is being ignored (ps aux shows the process still running as well) - sadmicrowave
@eumiro I've also tried to re-raise the KeyboardInterrupt exception by adding raise KeyboardInterrupt() within the first except KeyboardInterrupt: however I'm still experiencing the same issue. - sadmicrowave

1 Answers

15
votes

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.