2015-04-02 77 views
0

我正在編寫控制檯程序。我想只有在回答問題後,保存流纔可能與Cntr-c斷開:你真的想要打破它嗎?如何忽略python中的KeyboardInterrupt?

def sigint_handler(signal, frame): 
    try: 
     Exit = (str(raw_input("Break ? Y/N"))) 
     if Exit == "Y" or Exit=="y": 
      raise KeyboardInterrupt() 
    except KeyboardInterrupt: 
     raise KeyboardInterrupt() 
    except Exception as e: 
     pass 

signal.signal(signal.SIGINT,sigint_handler) 
i=0 

while i<1000: 
    i=i+1 
    print "%d\n"%i 
    sleep(0.5) 

,如果我嘗試CNTL + C,而不是Y的它的失敗:

71

72

73

74

75

^CBreak ? Y/Ny

File "/home.local/valerys/rde_1_3/rdepyui/bin/../api/cli.py", line 48, in sigint_handler Exit = (str(raw_input("Break ? Y/N"))) RuntimeError: can't re-enter readline

回答

3

你爲什麼讓在exceptKeyboardInterrupt再加薪?通過這種方式,您可以捕獲第一個KeyboardInterrupt,但您沒有另外的嘗試/除了第二個塊。也許更好的解決方案是撥打

try: 
    Exit = (str(raw_input("Break ? Y/N"))) 
    if Exit == "Y" or Exit=="y": 
     raise KeyboardInterrupt() 
except KeyboardInterrupt: 
    sys.exit() 

爲乾淨的退出策略。 我希望這可以幫助你。

+0

爲什麼不直接退出,沒有引發異常? – Pynchia 2015-04-02 09:05:37

+2

@Pynchia:我想這個異常引發是爲了這個簡化版本的代碼中沒有顯示的其他目的而需要的,但是除此之外,我沒有看到任何理由引發這個異常。 – 2015-04-02 09:12:23

+0

這是CLI,我希望該用戶不取消執行程序流程。 – 2015-09-09 04:40:59