亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

Python捕獲全局的KeyboardInterrupt異常的方法實(shí)現(xiàn)

 更新時(shí)間:2024年08月20日 10:37:21   作者:Looooking  
KeyboardInterrupt異常是Python中的一個(gè)標(biāo)準(zhǔn)異常,它通常發(fā)生在用戶通過鍵盤中斷了一個(gè)正在運(yùn)行的程序,本文主要介紹了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)文章

最新評論