python捕獲KeyboardInterrupt異常
命令行程序運行期間,如果用戶想終止程序,一般都會采用Ctrl-C快捷鍵,這個快捷鍵會引發python程序拋出KeyboardInterrupt異常。我們可以捕獲這個異常,在用戶按下Ctrl-C的時候,進行一些清理工作。
從python自帶的異常對象來看,與退出程序有關的異常,都繼承自BaseException。KeyboardInterrupt異常也在其中。因此,我們要捕獲這個異常,就要以如下方式寫python代碼:
try:
# many code here
except BaseException as e:
if isinstance(e, KeyboardInterrupt):
# ctrl-c goes here
這段代碼在except中使用isinstance函數來判斷具體是哪一個異常發生了,這種寫法可以區分具體的異常,進而分別處理。
或者,直接在except語句中對接KeyboardInterrupt異常:
try:
# many code here
except KeyboardInterrupt as e:
# do something
注意,協程except Exception將無法捕獲KeyboardInterrupt異常。