python捕获KeyboardInterrupt异常

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异常。

posted @ 2021-12-30 14:34  嗨,阿良  阅读(13441)  评论(0编辑  收藏  举报