Python捕獲全局的KeyboardInterrupt異常的方法實現(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
一般情況下,程序運行過程當(dāng)中要執(zhí)行的代碼量會比較大,一般用戶執(zhí)行 Ctrl + C 程序就報錯 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
但是有時候,我們希望用戶在 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異常的方法實現(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實現(xiàn)FTP服務(wù)器服務(wù)的方法
本篇文章主要介紹了python實現(xiàn)FTP服務(wù)器的方法,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2017-04-04pandas 數(shù)據(jù)歸一化以及行刪除例程的方法
今天小編就為大家分享一篇pandas 數(shù)據(jù)歸一化以及行刪除例程的方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-11-11python 借助numpy保存數(shù)據(jù)為csv格式的實現(xiàn)方法
今天小編就為大家分享一篇python 借助numpy保存數(shù)據(jù)為csv格式的實現(xiàn)方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-07-07