Dbus信号中的嵌套dict

2024-04-16 20:08:40 发布

您现在位置:Python中文网/ 问答频道 /正文

有阶级 在

class MyService(dbus.service.Object):
  def __init__(self):
    bus_name = dbus.service.BusName(__dbus_object_name__, bus=dbus.SessionBus())
    dbus.service.Object.__init__(self, bus_name, __dbus_object_path__)

  @dbus.service.signal(__dbus_object_name__, signature='a{sv}')
  def TickSignal(self, info):
    print(info)
s = MyService()

尝试发送嵌套的措辞

s.TickSignal({'a':'b','b':1,'c':{'a':'a'}})工作正常,但是如果嵌套dict包含数字,则会导致异常

s.TickSignal({'a':'b','b':1,'c':{'a':'a','b':1}})

^{pr2}$

Tags: nameselfinfoobjectinitdefserviceclass
2条回答

您可以使用如下嵌套词典:

self._properties = dbus.Dictionary({
            'Metadata': dbus.Dictionary({
                'mpris:length': dbus.Int64(2400000000),
                'mpris:artUrl': 'file:///home/user/1.jpg',
                'xesam:artist': ['1', '2'],
                'xesam:title': 'hello world',
                'xesam:url': '',
                'xesam:album': 'hehe'
            }, signature='sv'),
            'CanControl': True
        }, signature='sv')

它应该有用。在

如果没有显式指定签名,您使用的D-Bus绑定(dbus-python)将假定字典中的所有类型都与字典中的任意项相同。在本例中,dbuspython假设字典中的所有条目都是“ss”。在

dbus-python tutorial

Dictionaries are represented by Python dictionaries, or by dbus.Dictionary, a subclass of dict. When sending a dictionary, if an introspected signature is available, that will be used; otherwise, if the signature keyword parameter was passed to the Dictionary constructor, that will be used to determine the contents' key and value signatures; otherwise, dbus-python will guess from an arbitrary item of the dict.

所以你需要指出字典中的类型。显式指定签名的一种方法是创建如下数据:

inner = dbus.Dictionary({'a': 'a', 'b': 1}, signature='sv')
outer = dbus.Dictionary({'a': 'b', 'b': 1, 'c': inner}, signature='sv')
s.TickSignal(outer)

希望这有帮助。在

相关问题 更多 >