繁体   English   中英

dbus变体:如何在Python中保留布尔数据类型?

[英]dbus Variant: How to preserve boolean datatype in Python?

我最近一直在尝试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)之前完成了此检查isinstance(value, int)则不会有问题。 有任何想法吗?

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

为了将DBus客户端与以任何语言编写的服务进行通信,Python本机类​​型将转换为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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM