首页 > 解决方案 > KeyboardInterrupt 不能在父类方法中被捕获

问题描述

我有一个父类,其中有一个try子句,一个子类覆盖try子句内的一个方法。当孩子抚养它时,可以捕获正常的异常。但是,无法捕获键盘中断异常。此外,它可以在子方法内部捕获,但不能在父方法内部捕获。

请看下面的示例代码,其中中断不能被捕获bar1,但可以在bar2将其更改为断言错误后被捕获。我在 Linux 和 Windows 的 python 3.6 中产生了这个问题。

import time
class foo:
    def body(self):
        pass
    def run(self):
        try:
            self.body()
        except Exception as ex:
            print("caught exception:", str(ex))

class bar1(foo):
    def body(self):
        while(1):
            print(1)
            time.sleep(0.1)

class bar2(foo):
    def body(self):
        interrupted = False
        while(1):
            assert not interrupted, "assert not interrupted"
            try:
                print(1)
                time.sleep(0.1)
            except KeyboardInterrupt as ex:
                print("received interrupt")
                interrupted = True

中断类bar1获取的run方法

1
....
1
Traceback (most recent call last):
  File "tmp.py", line 34, in <module>
    b.run()
  File "tmp.py", line 7, in run
    self.body()
  File "tmp.py", line 15, in body
    time.sleep(0.1)
KeyboardInterrupt

然而,打断bar2得到

1
...
1
received interrupt
caught exception: assert not interrupted

我搜索了 StackOverflow 并发现了一些关于使用线程stdIO处理键盘中断的问题,但我没有发现这样的问题。

标签: pythonexception

解决方案


推荐阅读