Python和d-bus:如何设置主循环?

f4l*_*lco 11 python dbus pygobject

我有python和dbus的问题.我查看了开发人员文档和规范,但我不明白如何设置主循环.我想听通知事件.看到

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

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

我的示例脚本:

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()
Run Code Online (Sandbox Code Playgroud)

DBusGMainLoop没有像run()这样的其他方法.如果我使用gobject的循环并更改源代码:

import gobject
loop = gobject.MainLoop()
dbus.set_default_main_loop(loop)
...
loop.run()
Run Code Online (Sandbox Code Playgroud)

我收到以下错误消息:

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
Run Code Online (Sandbox Code Playgroud)

知道该怎么办吗?提前致谢.菲尼亚斯

Dan*_*Dan 7

放在import gobject代码的顶部,并在实例化对象后,执行gobject.MainLoop().run().我认为MainLoop必须在创建之后DBusGMainLoop创建.

  • 非常感谢,它现在有效.主循环的构造不是很明显,是吗? (3认同)