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

2

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

Mesozoic answered 8/11, 2010 at 15:45 Comment(0)
H
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.

Hluchy answered 9/11, 2010 at 0:32 Comment(1)
thanks a lot, it works now. The construction of a main loop isn't very obvious, is it?Mesozoic
S
-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.

Sikang answered 26/8, 2018 at 11:9 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.