2

我最近一直在尝试使用 dbus。但我似乎无法让我的 dbus 服务猜测布尔值的正确数据类型。考虑以下示例:

import gtk
import dbus
import dbus.service
from dbus.mainloop.glib import DBusGMainLoop

class Service(dbus.service.Object):

  def __init__(self):
    bus_name = dbus.service.BusName("org.foo.bar", bus = dbus.SessionBus())
    dbus.service.Object.__init__(self, bus_name, "/org/foo/bar")


  @dbus.service.method("org.foo.bar", in_signature = "a{sa{sv}}",
    out_signature = "a{sa{sv}}")
  def perform(self, data):   
    return data


if __name__ == "__main__":
  DBusGMainLoop(set_as_default = True)
  s = Service()
  gtk.main()

这段代码创建了一个 dbus 服务,该服务提供 perform 方法,该方法接受一个参数,该参数是一个字典,该字典从字符串映射到其他字典,而后者又将字符串映射到变体。我之所以选择这种格式,是因为我的字典采用的格式:

{
  "key1": {
    "type": ("tuple", "value")
  },
  "key2": {
    "name": "John Doe",
    "gender": "male",
    "age": 23
  },
  "test": {
    "true-property": True,
    "false-property": False
  }
}

当我通过我的服务传递这个字典时,布尔值被转换为整数。在我看来,检查应该没有那么困难。考虑一下(value是要转换为 dbus 类型的变量):

if isinstance(value, bool):
  return dbus.Boolean(value)

如果在检查之前完成此检查,isinstance(value, int)则没有问题。有任何想法吗?

4

1 回答 1

0

我不确定你在哪个部分有困难。正如您在示例中所示,可以轻松地将类型从一种形式转换为另一种形式dbus.Boolean(val)。您还可以使用isinstance(value, dbus.Boolean)来测试该值是否是 dbus 布尔值,而不是整数。

Python 本机类型被转换为dbus类型,以便在 DBus 客户端和以任何语言编写的服务之间进行通信。因此,任何发送到 DBus 服务/从 DBus 服务接收的数据都将包含dbus.*数据类型。

def perform(self, data):
    for key in ['true-property', 'false-property']:
        val = data['test'][key]
        newval = bool(val)

        print '%s type: %s' % (key, type(val))
        print 'is dbus.Boolean: %s' % isinstance(val, dbus.Boolean)
        print 'Python:', newval
        print '  Dbus:', dbus.Boolean(newval)
    return data

输出:

true-property type: <type 'dbus.Boolean'>
is dbus.Boolean: True
Python: True
  Dbus: 1
false-property type: <type 'dbus.Boolean'>
is dbus.Boolean: True
Python: False
  Dbus: 0
于 2011-04-26T15:03:38.730 回答