D-Bus python 服务示例

D-Bus python service example

我在 运行 最简单的 D-Bus 服务时遇到问题。这是我尝试使用的代码

#!/usr/bin/python3
from gi.repository import GLib
import dbus
import dbus.service
from dbus.mainloop.glib import DBusGMainLoop

class Example(dbus.service.Object):
    def __init__(self, object_path):
        dbus.service.Object.__init__(self, dbus.SessionBus(), object_path)
        self._last_input = None

    @dbus.service.method(dbus_interface='com.example.Sample',
                         in_signature='v', out_signature='s')
    def StringifyVariant(self, var):
        self.LastInputChanged(var)      # emits the signal
        return str(var)

    @dbus.service.signal(dbus_interface='com.example.Sample',
                         signature='v')
    def LastInputChanged(self, var):
        # run just before the signal is actually emitted
        # just put "pass" if nothing should happen
        self._last_input = var

    @dbus.service.method(dbus_interface='com.example.Sample',
                         in_signature='', out_signature='v')
    def GetLastInput(self):
        return self._last_input

if __name__ == '__main__':
    dbus.mainloop.glib.DBusGMainLoop(set_as_default=True)

    session_bus = dbus.SessionBus()
    name = dbus.service.BusName("com.example.SampleService", session_bus)
    object = Example('/com/example/Sample')

    mainloop = GLib.MainLoop()
    print ("Running sample service.")
    mainloop.run()

然后我添加了/usr/share/dbus-1/services/com.example.Sample.service

[D-BUS Service]
Name=com.example.Sample
Exec=/home/me/dbus_test/service.py

权限正确:

~/dbus_test $ ll
-rwxrwxr-x  1 me me 1345 Jun  3 19:52 service.py*

但是我无法连接到该服务

$ dbus-send --session  --dest="com.example.Sample" --type="method_call" --print-reply "/com/example/Sample" "com.example.Sample.GetLastInput"

Error org.freedesktop.DBus.Error.NoReply: Did not receive a reply. Possible causes include: the remote application did not send a reply, the message bus security policy blocked the reply, the reply timeout expired, or the network connection was broken.

我刚超时。

我错过了什么?

谢谢

您的服务名称是 com.example.SampleService 但您的测试客户端使用 com.example.Sample 作为目的地(并且服务文件有同样的错误)。

我建议使用 d-feet 到 'debug' D-Bus:像这样的错误在那里更容易发现。