5

當按下Ctrl + C時,我的while循環不會退出。它似乎忽略了我的KeyboardInterrupt異常。環路部分看起來是這樣的:python退出無限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 

同樣,我不知道是什麼問題,但我從來沒有終端甚至打印兩個打印提醒我在我的異常。有人可以幫我解決這個問題嗎?

+2

您的第一個'除了KeyboardInterrupt'捕獲異常。如果你不重新提高它,第二個'except(KeyboardInterrupt,SystemExit)'不可見。 – eumiro 2011-12-27 14:23:59

+0

@eumiro - 我註釋掉了第一個KeyboardInterrupt,並用'pass'替換了異常的內容,但我仍然遇到同樣的問題。 Ctrl + C被忽略(ps aux顯示進程仍然在運行) – sadmicrowave 2011-12-27 14:30:42

+0

@eumiro我也試圖通過在第一個'除KeyboardInterrupt:'之外添加'raise KeyboardInterrupt()'來重新引發KeyboardInterrupt異常。我仍然遇到同樣的問題。 – sadmicrowave 2011-12-27 14:50:49

回答

11

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塊的兩個打印語句應執行「(再次)」出現的第二位。

+0

雖然您沒有問過這個問題,但代碼中的'pass'語句會創建所謂的旋轉鎖。旋轉鎖不必要地佔用CPU,並可能影響整個系統的性能。有辦法避免它們。使用'Queue.Queue'對象進行線程之間的通信,使用'select.select'或'multiprocessing'模塊來進行進程之間的通信。 – wberry 2011-12-27 15:07:29

+0

所以,我發現我的主要問題(我認爲是無關的)是我已經分叉我的腳本兩次'守護'它。既然如此,KeyboardInterrupt不再連接到同一個終端(不過,我的腳本仍然會將輸出打印到活動終端)。有沒有辦法在守護程序中繼續使用KeyboardInterrupt(或另一種手動結束我的腳本)? – sadmicrowave 2011-12-27 15:22:38

+0

目前我一直在'ps aux'輸出中尋找processid並執行'sudo kill [pid]';不過,在殺死它之前,這並沒有優雅地清理我的代碼。在殺死程序之前,我需要關閉數據庫連接並刪除inotify手錶。 – sadmicrowave 2011-12-27 15:24:36