PyGObject GLib.MainLoop()和异常 [英] PyGObject GLib.MainLoop() and exceptions

查看:138
本文介绍了PyGObject GLib.MainLoop()和异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在Python应用程序中使用PyGObject中的GLib.MainLoop(),并且有一个问题.

I'm using GLib.MainLoop() from PyGObject in my Python application and have a question.

是否可以处理在loop.run()中引发的Python异常?

Is it possible to handle Python exception that raises in loop.run()?

例如,我正在使用GLib.MainContext.invoke_full()调用某些函数:

For example I'm calling some function using GLib.MainContext.invoke_full():

import traceback, gi
from gi.repository import GLib

try:
    loop = GLib.MainLoop()

    def handler(self):
        print('handler')
        raise Exception('from handler with love')

    loop.get_context().invoke_full(GLib.PRIORITY_DEFAULT, handler, None)
    loop.run()

except Exception:
    print('catched!')

我认为handler()应该在loop.run()内部的某个地方调用,因此raise Exception('from handler with love')应该被except Exception:捕获.但是,不是:

I thought that handler() should be called somewhere inside loop.run() so raise Exception('from handler with love') should be catched by except Exception:. However, it is not:

$ python test.py 
handler
Traceback (most recent call last):
  File "test.py", line 9, in handler
    raise Exception('from handler with love')
Exception: from handler with love

似乎handler()在不知道发生的地方被调用(是从GLibC代码调用的?),而没有被except Exception:捕获.

It seems that handler() called in the middle of nowhere (called from GLib's C code?), and not catched by except Exception:.

是否可以捕获在GLib.MainLoop.run()中引发的所有Python异常?我有一打这样的处理程序,所以我必须在每个处理程序中添加相同的try: ... except OneException: ... exceptAnotherException: ...包装器.

Is it possible to catch all Python exceptions that raises in GLib.MainLoop.run()? I have a dozen of handlers called like that so I have to add same try: ... except OneException: ... exceptAnotherException: ... wrapper into each handler.

推荐答案

否,不会传播该异常.它被捕获并打印. Python回调中没有异常会导致循环退出.

No, the exception is not propagated. It is caught and printed. No exception in a Python callback causes the loop to exit.

这篇关于PyGObject GLib.MainLoop()和异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆