用Python监控DBus消息

3

我正在尝试制作一个Python应用程序,它可以读取通过DBus传递的消息,并输出与bash dbus-monitor相同的结果。根据我的搜索结果,代码应该非常简单明了,就像这样:

import dbus, gobject
from dbus.mainloop.glib import DBusGMainLoop

def msg_cb(bus, msg):
    args = msg.get_args_list()
    print "Notification from '%s'" % args[0]
    print "Summary: %s" % args[3]
    print "Body: %s", args[4]

if __name__ == '__main__':
    DBusGMainLoop(set_as_default=True)
    bus = dbus.SessionBus()

    string = "interface='org.freedesktop.Notifications',member='Notify'"
    bus.add_match_string(string)
    bus.add_message_filter(msg_cb)

    mainloop = gobject.MainLoop ()
    mainloop.run ()

但是,当我启动它时,DBus返回的消息只是应用程序已连接,与我执行bash命令时得到的不同:

dbus-monitor --session interface='org.freedesktop.Notifications',member='Notify'

在这种情况下,我可以查看所有与筛选条件匹配的消息。有人能帮助我理解我哪里出错了吗?谢谢。

这可能不是你问题的答案,但安装qt4-dev-tools并启动qtdbusviewer可能值得一试。我经常用它来调试我的dbus代码。如果你在命令行上运行它,它可能会在输出中显示dbus消息。干杯。 - NuclearPeon
看起来语法在短短的两年内就发生了很大变化。至少在我的Python 2.7.8上,我再也无法使用“printf-C-style”语法输出任何print信息了,尽管获取消息的方式对我来说似乎是正确的。 - syntaxerror
1个回答

10

Notify 是一种方法,而不是一个信号,所以您需要将 eavesdrop='true' 添加为匹配规则的一部分,以接收那些并非针对您的消息。 如果您运行 dbus-monitor,则会注意到 dbus-monitor 设置中的 eavesdrop 键。

我相信这是自 dbus-1.5.6 以来的行为变化,当时修复了 问题 39450


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接