问题
I've been experimenting with dbus lately. But I can't seem to get my dbus Service to guess the correct datatypes for boolean values. Consider the following example:
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()
This piece of code creates a dbus service that provides the perform method which accepts one parameter that is a dictionary which maps from strings to other dictionaries, which in turn map strings to variants. I have chosen this format because of the format my dictionaries are in:
{
"key1": {
"type": ("tuple", "value")
},
"key2": {
"name": "John Doe",
"gender": "male",
"age": 23
},
"test": {
"true-property": True,
"false-property": False
}
}
When I pass this dictionary through my service, the boolean values are converted to integers. In my eyes, the check should not be that difficult. Consider this (value
is the variable to be converted to a dbus type):
if isinstance(value, bool):
return dbus.Boolean(value)
If this check is done before checking for isinstance(value, int)
then there would be no problem.
Any ideas?
回答1:
I'm not sure which part you're having difficulty with. The types can easily be cast from one form to another, as you show in your example dbus.Boolean(val)
. You can also use isinstance(value, dbus.Boolean)
to test if the value is a dbus boolean, not an integer.
The Python native types are converted into dbus
types in order to enable communicate between DBus clients and services written in any language. So any data sent to / received from a DBus service will consist of dbus.*
data types.
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
Output:
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
来源:https://stackoverflow.com/questions/5791095/dbus-variant-how-to-preserve-boolean-datatype-in-python