dbus变体:如何在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)
之前先进行这个检查,那就不会有问题了。有什么想法吗?
1 个回答
0
我不太确定你在哪个部分遇到了困难。你可以很简单地把不同类型的数据转换成另一种形式,就像你在例子中展示的 dbus.Boolean(val)
。你还可以用 isinstance(value, dbus.Boolean)
来检查一个值是不是 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