13

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

f4lco
  • 3,728
  • 5
  • 28
  • 53

2 Answers2

9

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.

Dan
  • 2,766
  • 3
  • 27
  • 28
  • 3
    thanks a lot, it works now. The construction of a main loop isn't very obvious, is it? – f4lco Nov 10 '10 at 06:31
-1

I had the same problem. After getting my code to work, I came across this question.

Dan's answer is partially correct. You import gobject first, but you can also instantiate your MainLoop before the DBusGMainLoop is created. You should run it after the DBusGMainLoop is created.

Tushar Vazirani
  • 1,011
  • 13
  • 14