Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python and d-bus: How to set up main loop?

I have a problem with python and dbus. I checked out the developer docs and specifications, but I don't understand how to set up a main loop. I want to listen for notification events. See

http://dbus.freedesktop.org/doc/dbus-python/doc/

and

http://www.galago-project.org/specs/notification/0.9/index.html

My example script:

import dbus
from dbus.mainloop.glib import DBusGMainLoop

class MessageListener:

    def __init__(self):

        DBusGMainLoop(set_as_default=True)

        self.bus = dbus.SessionBus()
        self.proxy = self.bus.get_object('org.freedesktop.Notifications',
            '/org/freedesktop/Notifications')

        self.proxy.connect_to_signal('NotificationClosed',
            self.handle_notification)

    def handle_notification(self, *args, **kwargs):
        print args, kwargs


if __name__ == '__main__':
    MessageListener()

DBusGMainLoop has no further methods like run(). If I use a loop from gobject and change the sourcecode:

import gobject
loop = gobject.MainLoop()
dbus.set_default_main_loop(loop)
...
loop.run()

I get following error message:

Traceback (most recent call last):
  File "dbus_example.py", line 40, in <module>
    MessageListener()
  File "dbus_example.py", line 9, in __init__
    dbus.set_default_main_loop(loop)
TypeError: A dbus.mainloop.NativeMainLoop instance is required

Any idea what to do about it? Thanks in advance. phineas

like image 293
f4lco Avatar asked Nov 08 '10 15:11

f4lco


1 Answers

Put import gobject at the top of your code, and after instantiating your object, do gobject.MainLoop().run(). I think that the MainLoop has to be created after the DBusGMainLoop is created.

like image 196
Dan Avatar answered Sep 18 '22 11:09

Dan