使用 Python 注册 "Hello World" DBus 服务、对象和方法

Register a "Hello World" DBus service, object and method using Python

我正在尝试导出名为 com.example.HelloWorld 的 DBus 服务,其中包含对象 /com/example/HelloWorld 和方法 com.example.HelloWorld.SayHello,如果使用

dbus-send --system --type=method_call --dest=com.example.HelloWorld /com/example/HelloWorld com.example.HelloWorld.SayHello

所以我的问题是如何使用一种打印 "hello, world"(在其自己的标准输出上)的方法制作简单的 DBus 服务。

使用 dbus-python 时,导出 D-Bus 服务的以下设置有效:

import gobject
import dbus
import dbus.service

from dbus.mainloop.glib import DBusGMainLoop
DBusGMainLoop(set_as_default=True)


OPATH = "/com/example/HelloWorld"
IFACE = "com.example.HelloWorld"
BUS_NAME = "com.example.HelloWorld"


class Example(dbus.service.Object):
    def __init__(self):
        bus = dbus.SessionBus()
        bus.request_name(BUS_NAME)
        bus_name = dbus.service.BusName(BUS_NAME, bus=bus)
        dbus.service.Object.__init__(self, bus_name, OPATH)

    @dbus.service.method(dbus_interface=IFACE + ".SayHello",
                         in_signature="", out_signature="")
    def SayHello(self):
        print "hello, world"


if __name__ == "__main__":
    a = Example()
    loop = gobject.MainLoop()
    loop.run()

该示例是根据您的代码修改的,其中包含如何为 dbus-python 设置主循环,其中包含以下几行:

from dbus.mainloop.glib import DBusGMainLoop
DBusGMainLoop(set_as_default=True)

主循环在示例的最后一节中初始化服务后启动:

if __name__ == "__main__":
    a = Example()
    loop = gobject.MainLoop()
    loop.run()

上面的完整示例可以通过调用 dbus-send 来调用,如下所示:

dbus-send --session --print-reply --type=method_call --dest=com.example.HelloWorld /com/example/HelloWorld com.example.HelloWorld.SayHello.SayHello

请注意,这一行也是通过指定 --session 而不是 --system 从您的问题中修改的,并且指定要调用的方法的方法是将方法名称附加到接口,因此我们在那里有双 SayHello 部分。如果这不是预期的,您可以在服务中导出方法时从界面中删除添加的 SayHello,如下所示:

# only 'IFACE' is used here
@dbus.service.method(dbus_interface=IFACE,
                     in_signature="", out_signature="")

然后可以这样调用服务:

dbus-send --session --print-reply --type=method_call --dest=com.example.HelloWorld /com/example/HelloWorld com.example.HelloWorld.SayHello

另见例如How to use the existing services in DBus? for more examples of minimal service and client code, and Role of Mainloops, Event Loops in DBus service 了解有关主循环内容的一些信息。