python退出無限循環與KeyboardInterrupt異常


參考:http://www.voidcn.com/article/p-pmlncsni-bvo.html

 

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

同樣,我不確定問題是什么,但我的終端甚至從未打印過我的異常中的兩個打印警報.有人能幫我解決這個問題嗎?

 
用raise語句替換break語句,如下所示:

 

 

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語句應該以'(再次)’出現的第二個執行.

 
 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM