2011-08-09 61 views
6

是否有反正我可以讓我的腳本執行我的一個功能,當腳本運行時點擊Ctrl+c如何覆蓋鍵盤中斷? (Python)

+0

請參閱http://stackoverflow.com/questions/4205317/capture-keyboardinterrupt-in-python-without-try-except若干選項。 – DSM

回答

18

看看signal handlers。 CTRL-C對應於SIGINT(posix系統上的信號#2)。

例子:

#!/usr/bin/env python 
import signal 
import sys 
def signal_handler(signal, frame): 
    print 'You pressed Ctrl+C - or killed me with -2' 
    sys.exit(0) 
signal.signal(signal.SIGINT, signal_handler) 
print 'Press Ctrl+C' 
signal.pause() 
+0

注意:當你在OS – wim

+0

@wim中執行'kill -2 [pid]'時,這個應該也會觸發信號處理程序,謝謝,給我的答案增加了一個提示 - 實際上是否有區分kill的方法通過殺死鍵盤從殺死? – miku

+1

我見過前者會在Python中引發'KeyboardInterrupt'異常,後者則不會。但我不確定爲什麼會這樣。 – wim

5

當然。

try: 
    # Your normal block of code 
except KeyboardInterrupt: 
    # Your code which is executed when CTRL+C is pressed. 
finally: 
    # Your code which is always executed.