python - 处理 glib 主循环中未捕获的错误
问题描述
我想在 glib 主循环中添加类似默认错误处理程序的东西来捕获和处理未捕获的错误。
GLib主循环不会停止执行错误,所以我猜GLib代码中存在某种错误处理程序,它只是打印它然后继续,好像什么也没发生一样。我想扩展那个错误处理程序来做一些自定义的事情。
from gi.repository import GLib
def throw():
raise ValueError('catch this error somehow without try and catch')
def stop():
print('exit')
exit()
GLib.timeout_add(100, throw)
GLib.timeout_add(200, stop)
GLib.MainLoop().run()
这打印
Traceback (most recent call last):
File "gtkasyncerror.py", line 7, in throw
raise ValueError('catch this error somehow without try and catch')
ValueError: catch this error somehow without try and catch
exit
这就是我希望它的工作方式:
def error_handler(e):
# do funny stuff
# the ValueError from above should be in e
loop = GLib.MainLoop()
loop.error_handler = error_handler
GLib.MainLoop().run()
解决方案
https://stackoverflow.com/a/6598286/4417769
import sys
from gi.repository import GLib
def throw():
raise ValueError('catch this error somehow without try and catch')
try:
raise ValueError('this should not be handled by error_handler')
except ValueError as e:
pass
def stop():
print('exit')
exit()
def error_handler(exctype, value, traceback):
print('do funny stuff,', value)
GLib.timeout_add(100, throw)
GLib.timeout_add(200, stop)
sys.excepthook = error_handler
GLib.MainLoop().run()
输出:
do funny stuff, catch this error somehow without try and catch
exit
推荐阅读
- powershell - 无法在 DevOps 上并行执行 Powershell 7 脚本
- reactjs - Material-ui 自动完成警告 提供给自动完成的值无效。您可以使用 getOptionSelected` 属性自定义相等测试
- c# - 比较字符串变量并忽略外部空格
- python - 如何在python中提取文本的最后一部分
- rest - 无法使用 golang 测试和 beego 框架验证具有预期输出的 Http 响应
- javascript - Why is this function definition ignored?
- node.js - 使用for循环在nodejs中运行多个post请求不起作用
- dji-sdk - 获取速度并计算加速度 DJI SDK
- android - 如何以编程方式更改wifi代理android?
- python - 如何使用python在pdf文件中查找发票表的区域坐标?