Search code examples
pythonglib

PyGObject GLib.MainLoop() and exceptions


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

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

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!')

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

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

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.


Solution

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