Python捕獲全局的KeyboardInterrupt異常的方法實(shí)現(xiàn)
當(dāng)然,像下面這種情況。
你要是把所有代碼像下面那樣都放到 try, except 的情況,就當(dāng)我什么也沒說。
import time def main(): print('before ...') time.sleep(10) print('after ...') if __name__ == '__main__': try: main() except KeyboardInterrupt: print('\nKeyboardInterrupt ...') print('the end')
root@master ~/w/python3_learning# python3 test.py before ... ^C KeyboardInterrupt ... the end
一般情況下,程序運(yùn)行過程當(dāng)中要執(zhí)行的代碼量會(huì)比較大,一般用戶執(zhí)行 Ctrl + C 程序就報(bào)錯(cuò) KeyboardInterrupt 停止了。
import time def main(): print('before ...') time.sleep(10) print('after ...') if __name__ == '__main__': main() print('the end')
root@master ~/w/python3_learning# python3 test.py before ... ^CTraceback (most recent call last): File "test.py", line 11, in <module> main() File "test.py", line 6, in main time.sleep(10) KeyboardInterrupt
但是有時(shí)候,我們希望用戶在 Ctrl + C 之后再繼續(xù)執(zhí)行一些清理操作。
import sys import time def suppress_keyboard_interrupt_message(): old_excepthook = sys.excepthook def new_hook(exctype, value, traceback): if exctype != KeyboardInterrupt: old_excepthook(exctype, value, traceback) else: print('\nKeyboardInterrupt ...') print('do something after Interrupt ...') sys.excepthook = new_hook def main(): print('before ...') time.sleep(10) print('after ...') if __name__ == '__main__': suppress_keyboard_interrupt_message() main() print('the end')
root@master ~/w/python3_learning# python3 test.py before ... ^C KeyboardInterrupt ... do something after Interrupt ...
由于 suppress_keyboard_interrupt_message 函數(shù)中的 new_hook 是自定義的,所以你也不一定局限于只處理某種異常,甚至對所有異常做統(tǒng)一處理也是可以的。
到此這篇關(guān)于Python捕獲全局的KeyboardInterrupt異常的方法實(shí)現(xiàn)的文章就介紹到這了,更多相關(guān)Python KeyboardInterrupt異常內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
python在CMD界面讀取excel所有數(shù)據(jù)的示例
這篇文章主要介紹了python在CMD界面讀取excel所有數(shù)據(jù),幫助大家更好的利用python辦公,感興趣的朋友可以了解下2020-09-09Python 含參構(gòu)造函數(shù)實(shí)例詳解
這篇文章主要介紹了Python 含參構(gòu)造函數(shù)實(shí)例詳解的相關(guān)資料,需要的朋友可以參考下2017-05-05Pycharm 解決自動(dòng)格式化沖突的設(shè)置操作
這篇文章主要介紹了Pycharm 解決自動(dòng)格式化沖突的設(shè)置操作,具有很好的參考價(jià)值,希望對大家有所幫助。一起跟隨小編過來看看吧2021-01-01python動(dòng)態(tài)視頻下載器的實(shí)現(xiàn)方法
這里向大家分享一下python爬蟲的一些應(yīng)用,主要是用爬蟲配合簡單的GUI界面實(shí)現(xiàn)視頻,音樂和小說的下載器。今天就先介紹如何實(shí)現(xiàn)一個(gè)動(dòng)態(tài)視頻下載器,需要的朋友可以參考下2019-09-09python實(shí)現(xiàn)FTP服務(wù)器服務(wù)的方法
本篇文章主要介紹了python實(shí)現(xiàn)FTP服務(wù)器的方法,小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2017-04-04pandas 數(shù)據(jù)歸一化以及行刪除例程的方法
今天小編就為大家分享一篇pandas 數(shù)據(jù)歸一化以及行刪除例程的方法,具有很好的參考價(jià)值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-11-11python 借助numpy保存數(shù)據(jù)為csv格式的實(shí)現(xiàn)方法
今天小編就為大家分享一篇python 借助numpy保存數(shù)據(jù)為csv格式的實(shí)現(xiàn)方法,具有很好的參考價(jià)值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-07-07