python - 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
解决方案
推荐阅读
- android - 未处理的异常:键入“列表”
' 不是类型 'List 的子类型 '颤动中的共享偏好 - python - PyQt QPushButton leaveEvent 同时按下 QPushButton
- mysql - 使用多个表的 SQL 查询
- java - 将 NDI 流保存到 mp4 时出现 FFMPEG 错误
- c# - 使用 C# 将文档插入 CosmosDB
- javascript - 如何在反应中访问它之外的.map()方法的索引
- vb.net - 位运算符 AND 不返回值
- css - CSS border-radius 改变背景角
- java - 使用公共键java创建两个映射的值的映射
- python - 在 Apex 中压缩字符串并将其解压缩 python