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):
keyboard什么意思中文# ctrl-c goes here
这段代码在except中使⽤isinstance函数来判断具体是哪⼀个异常发⽣了,这种写法可以区分具体的异常,进⽽分别处理。
或者,直接在except语句中对接KeyboardInterrupt异常:
try:
# many code here
except KeyboardInterrupt as e:
# do something
注意,协程except Exception将⽆法捕获KeyboardInterrupt异常。