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

13 投票
2 回答
12411 浏览
提问于 2025-04-16 06:44

我在使用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()

DBusGMainLoop没有像run()这样的其他方法。

如果我使用gobject的循环并修改源代码:

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

我会收到以下错误信息:

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

有没有人知道该怎么处理这个问题?谢谢大家。

phineas

2 个回答

-1

我也遇到过同样的问题。在我的代码能正常工作后,我看到了这个问题。

Dan的回答部分是对的。你需要先导入gobject,但你也可以在创建DBusGMainLoop之前先实例化你的MainLoop。然后在创建DBusGMainLoop之后再运行它。

9

在你的代码最上面加上 import gobject,然后在你创建对象之后,执行 gobject.MainLoop().run()。我觉得 MainLoop 这个东西得在 DBusGMainLoop 创建之后才能创建。

撰写回答