虽然 Martin 是对的,但它不适用于由 python 转换为 int 的布尔值(因为 bool不能被子类化)。
In [3]: print(dbus.Boolean(False))
0
不幸的是,递归转换器是保留布尔值的唯一方法。
这是一个示例实现:
import dbus
def python_to_dbus(data):
'''
convert python data types to dbus data types
'''
if isinstance(data, str):
data = dbus.String(data)
elif isinstance(data, bool):
# python bools are also ints, order is important !
data = dbus.Boolean(data)
elif isinstance(data, int):
data = dbus.Int64(data)
elif isinstance(data, float):
data = dbus.Double(data)
elif isinstance(data, list):
data = dbus.Array([python_to_dbus(value) for value in data], signature='v')
elif isinstance(data, dict):
data = dbus.Dictionary(data, signature='sv')
for key in data.keys():
data[key] = python_to_dbus(data[key])
return data
def dbus_to_python(data):
'''
convert dbus data types to python native data types
'''
if isinstance(data, dbus.String):
data = str(data)
elif isinstance(data, dbus.Boolean):
data = bool(data)
elif isinstance(data, dbus.Int64):
data = int(data)
elif isinstance(data, dbus.Double):
data = float(data)
elif isinstance(data, dbus.Array):
data = [dbus_to_python(value) for value in data]
elif isinstance(data, dbus.Dictionary):
new_data = dict()
for key in data.keys():
new_data[key] = dbus_to_python(data[key])
data = new_data
return data
为了使它更容易在处理 dbus 源数据的类中使用,您可以使用装饰器:
def convert_to_python(func):
def wrapper(*args, **kwargs):
return dbus_to_python(func(*args, **kwargs))
return wrapper
...
@convert_to_python
def dbus_method_call(self):
return self.dbus_proxy.Method()
这样,上面 dbus_method_call 返回的任何数据都将转换为原生 python。
请参阅此相关问题:dbus Variant: How to preserve boolean datatype in Python?