【问题标题】:Python and d-bus: How to set up main loop?Python 和 d-bus:如何设置主循环?
【发布时间】:2011-05-06 17:45:12
【问题描述】:

我对 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

知道该怎么做吗? 提前致谢。 飞哥

【问题讨论】:

    标签: python dbus pygobject


    【解决方案1】:

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

    【讨论】:

    • 非常感谢,现在可以使用了。主循环的构造不是很明显,是吗?
    【解决方案2】:

    我遇到了同样的问题。在让我的代码工作后,我遇到了这个问题。

    Dan 的回答部分正确。您首先导入 gobject,但您也可以在创建 DBusGMainLoop 之前实例化您的 MainLoop。您应该在创建 DBusGMainLoop 之后运行它。

    【讨论】:

      猜你喜欢
      • 2013-07-27
      • 2011-07-03
      • 2019-08-17
      • 2015-08-17
      • 1970-01-01
      • 1970-01-01
      • 2013-10-06
      • 1970-01-01
      • 2015-12-22
      相关资源
      最近更新 更多