Python Dbus:如何导出Interface属性

dei*_*mus 5 python dbus

在所有python dbus文档中都有关于如何导出对象,接口,信号的信息,但是没有任何方法可以导出接口属性.

任何想法如何做到这一点?

wjt*_*wjt 12

绝对可以在Python中实现D-Bus属性!D-Bus属性只是特定接口上的方法,即org.freedesktop.DBus.Properties.接口在D-Bus规范中定义; 你可以在你的类上实现它,就像你实现任何其他D-Bus接口一样:

# Untested, just off the top of my head

import dbus

MY_INTERFACE = 'com.example.Foo'

class Foo(dbus.service.object):
    # …

    @dbus.service.method(interface=dbus.PROPERTIES_IFACE,
                         in_signature='ss', out_signature='v')
    def Get(self, interface_name, property_name):
        return self.GetAll(interface_name)[property_name]

    @dbus.service.method(interface=dbus.PROPERTIES_IFACE,
                         in_signature='s', out_signature='a{sv}')
    def GetAll(self, interface_name):
        if interface_name == MY_INTERFACE:
            return { 'Blah': self.blah,
                     # …
                   }
        else:
            raise dbus.exceptions.DBusException(
                'com.example.UnknownInterface',
                'The Foo object does not implement the %s interface'
                    % interface_name)

    @dbus.service.method(interface=dbus.PROPERTIES_IFACE,
                         in_signature='ssv'):
    def Set(self, interface_name, property_name, new_value):
        # validate the property name and value, update internal state…
        self.PropertiesChanged(interface_name,
            { property_name: new_value }, [])

    @dbus.service.signal(interface=dbus.PROPERTIES_IFACE,
                         signature='sa{sv}as')
    def PropertiesChanged(self, interface_name, changed_properties,
                          invalidated_properties):
        pass
Run Code Online (Sandbox Code Playgroud)

dbus-python应该能够更容易地实现属性,但它目前的维护非常简单.

如果有人喜欢潜水并帮助修理这样的东西,他们会非常受欢迎.即使将这个样板的扩展版本添加到文档中也是一个开始,因为这是一个非常常见的问题.如果您有兴趣,可以将补丁发送到D-Bus邮件列表,或附加到FreeDesktop bugtracker上针对dbus-python提交的错误.

  • 我为[bug 26903](https://bugs.freedesktop.org/show_bug.cgi?id=26903)提供了添加属性的代码. (3认同)