【问题标题】:dbus Variant: How to preserve boolean datatype in Python?dbus Variant:如何在 Python 中保留布尔数据类型?
【发布时间】:2011-08-13 01:29:52
【问题描述】:

我最近一直在试验 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) 之前完成此检查,则不会有问题。 有什么想法吗?

【问题讨论】:

    标签: python gtk boolean dbus variant


    【解决方案1】:

    我不确定您在哪个部分遇到困难。正如您在示例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
    

    【讨论】:

    • 谢谢,您的回答让我找到了正确的解决方案。我正在将 dbus 类型转换为另一种格式。此转换使用检查 isinstance(value, bool)。这应该可以,但是dbus.Boolean 继承自int,因为bool cannot be subclassed。我只需要调整转换以检查 dbus.Boolean 实例。
    猜你喜欢
    • 2015-12-22
    • 1970-01-01
    • 2012-10-27
    • 1970-01-01
    • 2011-05-08
    • 2015-08-25
    • 2011-06-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多