5 :Author: Simon McVittie, `Collabora Ltd.`_
8 .. _`Collabora Ltd.`: http://www.collabora.co.uk/
10 This tutorial requires Python 2.4 or up, and ``dbus-python`` 0.80rc4 or up.
14 .. --------------------------------------------------------------------
22 Applications that use D-Bus typically connect to a *bus daemon*, which
23 forwards messages between the applications. To use D-Bus, you need to create a
24 ``Bus`` object representing the connection to the bus daemon.
26 There are generally two bus daemons you may be interested in. Each user
27 login session should have a *session bus*, which is local to that
28 session. It's used to communicate between desktop applications. Connect
29 to the session bus by creating a ``SessionBus`` object::
33 session_bus = dbus.SessionBus()
35 The *system bus* is global and usually started during boot; it's used to
36 communicate with system services like udev_, NetworkManager_, and the
37 `Hardware Abstraction Layer daemon (hald)`_. To connect to the system
38 bus, create a ``SystemBus`` object::
42 system_bus = dbus.SystemBus()
44 Of course, you can connect to both in the same application.
46 For special purposes, you might use a non-default Bus, or a connection
47 which isn't a Bus at all, using some new API added in dbus-python 0.81.0.
48 This is not described here, and will at some stage be the subject of a separate
52 http://www.kernel.org/pub/linux/utils/kernel/hotplug/udev.html
54 http://www.gnome.org/projects/NetworkManager/
55 .. _Hardware Abstraction Layer daemon (hald):
56 http://www.freedesktop.org/wiki/Software/hal
58 .. --------------------------------------------------------------------
63 D-Bus applications can export objects for other applications' use. To
64 start working with an object in another application, you need to know:
66 * The *bus name*. This identifies which application you want to
67 communicate with. You'll usually identify applications by a
68 *well-known name*, which is a dot-separated string starting with a
69 reversed domain name, such as ``org.freedesktop.NetworkManager``
70 or ``com.example.WordProcessor``.
72 * The *object path*. Applications can export many objects - for
73 instance, example.com's word processor might provide an object
74 representing the word processor application itself and an object for
75 each document window opened, or it might also provide an object for
76 each paragraph within a document.
78 To identify which one you want to interact with, you use an object path,
79 a slash-separated string resembling a filename. For instance, example.com's
80 word processor might provide an object at ``/`` representing the word
81 processor itself, and objects at ``/documents/123`` and
82 ``/documents/345`` representing opened document windows.
84 As you'd expect, one of the main things you can do with remote objects
85 is to call their methods. As in Python, methods may have parameters,
86 and they may return one or more values.
93 To interact with a remote object, you use a *proxy object*. This is a
94 Python object which acts as a proxy or "stand-in" for the remote object -
95 when you call a method on a proxy object, this causes dbus-python to make
96 a method call on the remote object, passing back any return values from
97 the remote object's method as the return values of the proxy method call.
99 To obtain a proxy object, call the ``get_object`` method on the ``Bus``.
100 For example, NetworkManager_ has the well-known name
101 ``org.freedesktop.NetworkManager`` and exports an object whose object
102 path is ``/org/freedesktop/NetworkManager``, plus an object per network
103 interface at object paths like
104 ``/org/freedesktop/NetworkManager/Devices/eth0``. You can get a proxy
105 for the object representing eth0 like this::
108 bus = dbus.SystemBus()
109 proxy = bus.get_object('org.freedesktop.NetworkManager',
110 '/org/freedesktop/NetworkManager/Devices/eth0')
111 # proxy is a dbus.proxies.ProxyObject
113 Interfaces and methods
114 ----------------------
116 D-Bus uses *interfaces* to provide a namespacing mechanism for methods.
117 An interface is a group of related methods and signals (more on signals
118 later), identified by a name which is a series of dot-separated components
119 starting with a reversed domain name. For instance, each NetworkManager_
120 object representing a network interface implements the interface
121 ``org.freedesktop.NetworkManager.Devices``, which has methods like
124 To call a method, call the method of the same name on the proxy object,
125 passing in the interface name via the ``dbus_interface`` keyword argument::
128 bus = dbus.SystemBus()
129 eth0 = bus.get_object('org.freedesktop.NetworkManager',
130 '/org/freedesktop/NetworkManager/Devices/eth0')
131 props = eth0.getProperties(dbus_interface='org.freedesktop.NetworkManager.Devices')
132 # props is a tuple of properties, the first of which is the object path
136 As a short cut, if you're going to be calling many methods with the same
137 interface, you can construct a ``dbus.Interface`` object and call
138 methods on that, without needing to specify the interface again::
141 bus = dbus.SystemBus()
142 eth0 = bus.get_object('org.freedesktop.NetworkManager',
143 '/org/freedesktop/NetworkManager/Devices/eth0')
144 eth0_dev_iface = dbus.Interface(eth0,
145 dbus_interface='org.freedesktop.NetworkManager.Devices')
146 props = eth0_dev_iface.getProperties()
147 # props is the same as before
152 See the example in ``examples/example-client.py``. Before running it,
153 you'll need to run ``examples/example-service.py`` in the background or
159 Unlike Python, D-Bus is statically typed - each method has a certain
160 *signature* representing the types of its arguments, and will not accept
161 arguments of other types.
163 D-Bus has an introspection mechanism, which ``dbus-python`` tries to use
164 to discover the correct argument types. If this succeeds, Python types
165 are converted into the right D-Bus data types automatically, if possible;
166 ``TypeError`` is raised if the type is inappropriate.
168 If the introspection mechanism fails (or the argument's type is
169 variant - see below), you have to provide arguments of
170 the correct type. ``dbus-python`` provides Python types corresponding to
171 the D-Bus data types, and a few native Python types are also converted to
172 D-Bus data types automatically. If you use a type which isn't among these,
173 a ``TypeError`` will be raised telling you that ``dbus-python`` was
174 unable to guess the D-Bus signature.
179 The following basic data types are supported.
181 ========================== ============================= =====
182 Python type converted to D-Bus type notes
183 ========================== ============================= =====
184 D-Bus `proxy object`_ ObjectPath (signature 'o') `(+)`_
185 `dbus.Interface`_ ObjectPath (signature 'o') `(+)`_
186 `dbus.service.Object`_ ObjectPath (signature 'o') `(+)`_
187 ``dbus.Boolean`` Boolean (signature 'b') a subclass of ``int``
188 ``dbus.Byte`` byte (signature 'y') a subclass of ``int``
189 ``dbus.Int16`` 16-bit signed integer ('n') a subclass of ``int``
190 ``dbus.Int32`` 32-bit signed integer ('i') a subclass of ``int``
191 ``dbus.Int64`` 64-bit signed integer ('x') `(*)`_
192 ``dbus.UInt16`` 16-bit unsigned integer ('q') a subclass of ``int``
193 ``dbus.UInt32`` 32-bit unsigned integer ('u') `(*)_`
194 ``dbus.UInt64`` 64-bit unsigned integer ('t') `(*)_`
195 ``dbus.Double`` double-precision float ('d') a subclass of ``float``
196 ``dbus.ObjectPath`` object path ('o') a subclass of ``str``
197 ``dbus.Signature`` signature ('g') a subclass of ``str``
198 ``dbus.String`` string ('s') a subclass of
200 ``dbus.UTF8String`` string ('s') a subclass of ``str``
201 ``bool`` Boolean ('b')
202 ``int`` or subclass 32-bit signed integer ('i')
203 ``long`` or subclass 64-bit signed integer ('x')
204 ``float`` or subclass double-precision float ('d')
205 ``str`` or subclass string ('s') must be valid UTF-8
206 ``unicode`` or subclass string ('s')
207 ========================== ============================= =====
211 Types marked (*) may be a subclass of either ``int`` or ``long``, depending
216 (+): D-Bus proxy objects, exported D-Bus service objects and anything
217 else with the special attribute ``__dbus_object_path__``, which
218 must be a string, are converted to their object-path. This might be
219 useful if you're writing an object-oriented API using dbus-python.
221 Basic type conversions
222 ~~~~~~~~~~~~~~~~~~~~~~
224 If introspection succeeded, ``dbus-python`` will also accept:
226 * for Boolean parameters, any object (converted as if via ``int(bool(...))``)
227 * for byte parameters, a single-character string (converted as if via ``ord()``)
228 * for byte and integer parameters, any integer (must be in the correct range)
229 * for object-path and signature parameters, any ``str`` or ``unicode``
230 subclass (the value must follow the appropriate syntax)
235 D-Bus supports four container types: array (a variable-length sequence of the
236 same type), struct (a fixed-length sequence whose members may have
237 different types), dictionary (a mapping from values of the same basic type to
238 values of the same type), and variant (a container which may hold any
239 D-Bus type, including another variant).
241 Arrays are represented by Python lists, or by ``dbus.Array``, a subclass
242 of ``list``. When sending an array, if an introspected signature is
243 available, that will be used; otherwise, if the ``signature`` keyword
244 parameter was passed to the ``Array`` constructor, that will be used to
245 determine the contents' signature; otherwise, ``dbus-python`` will guess
246 from the array's first item.
248 The signature of an array is 'ax' where 'x' represents the signature of
249 one item. For instance, you could also have 'as' (array of strings) or
250 'a(ii)' (array of structs each containing two 32-bit integers).
252 There's also a type ``dbus.ByteArray`` which is a subclass of ``str``,
253 used as a more efficient representation of a D-Bus array of bytes
256 Structs are represented by Python tuples, or by ``dbus.Struct``, a
257 subclass of ``tuple``. When sending a struct, if an introspected signature is
258 available, that will be used; otherwise, if the ``signature`` keyword
259 parameter was passed to the ``Array`` constructor, that will be used to
260 determine the contents' signature; otherwise, ``dbus-python`` will guess
261 from the array's first item.
263 The signature of a struct consists of the signatures of the contents,
264 in parentheses - for instance '(is)' is the signature of a struct
265 containing a 32-bit integer and a string.
267 Dictionaries are represented by Python dictionaries, or by
268 ``dbus.Dictionary``, a subclass of ``dict``. When sending a dictionary,
269 if an introspected signature is available, that will be used; otherwise,
270 if the ``signature`` keyword parameter was passed to the ``Dictionary``
271 constructor, that will be used to determine the contents' key and value
272 signatures; otherwise, ``dbus-python`` will guess from an arbitrary item
275 The signature of a dictionary is 'a{xy}' where 'x' represents the
276 signature of the keys (which may not be a container type) and 'y'
277 represents the signature of the values. For instance,
278 'a{s(ii)}' is a dictionary where the keys are strings and the values are
279 structs containing two 32-bit integers.
281 Variants are represented by setting the ``variant_level`` keyword
282 argument in the constructor of any D-Bus data type to a value greater
283 than 0 (``variant_level`` 1 means a variant containing some other data type,
284 ``variant_level`` 2 means a variant containing a variant containing some
285 other data type, and so on). If a non-variant is passed as an argument
286 but introspection indicates that a variant is expected, it'll
287 automatically be wrapped in a variant.
289 The signature of a variant is 'v'.
291 .. _byte_arrays and utf8_strings:
293 Return values, and the ``byte_arrays`` and ``utf8_strings`` options
294 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
296 If a D-Bus method returns no value, the Python proxy method will return
299 If a D-Bus method returns one value, the Python proxy method will return
300 that value as one of the ``dbus.`` types - by default, strings are
301 returned as ``dbus.String`` (a subclass of Unicode) and byte arrays are
302 returned as a ``dbus.Array`` of ``dbus.Byte``.
304 If a D-Bus method returns multiple values, the Python proxy method
305 will return a tuple containing those values.
307 If you want strings returned as ``dbus.UTF8String`` (a subclass of
308 ``str``) pass the keyword parameter ``utf8_strings=True`` to the proxy
311 If you want byte arrays returned as ``dbus.ByteArray`` (also a
312 subclass of ``str`` - in practice, this is often what you want) pass
313 the keyword parameter ``byte_arrays=True`` to the proxy method.
315 .. --------------------------------------------------------------------
317 Making asynchronous method calls
318 ================================
320 Asynchronous (non-blocking) method calls allow multiple method calls to
321 be in progress simultaneously, and allow your application to do other
322 work while it's waiting for the results. To make asynchronous calls,
323 you first need an event loop or "main loop".
325 Setting up an event loop
326 ------------------------
328 Currently, the only main loop supported by ``dbus-python`` is GLib.
330 ``dbus-python`` has a global default main loop, which is the easiest way
331 to use this functionality. To arrange for the GLib main loop to be the
334 from dbus.mainloop.glib import DBusGMainLoop
336 DBusGMainLoop(set_as_default=True)
338 You must do this before `connecting to the bus`_.
340 Actually starting the main loop is as usual for ``pygobject``::
344 loop = gobject.MainLoop()
347 While ``loop.run()`` is executing, GLib will run your callbacks when
348 appropriate. To stop, call ``loop.quit()``.
350 You can also set a main loop on a per-connection basis, by passing a
351 main loop to the Bus constructor::
354 from dbus.mainloop.glib import DBusGMainLoop
356 dbus_loop = DBusGMainLoop()
358 bus = dbus.SessionBus(mainloop=dbus_loop)
360 This isn't very useful until we support more than one main loop, though.
362 Backwards compatibility: ``dbus.glib``
363 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
365 In versions of ``dbus-python`` prior to 0.80, the way to set GLib as the
366 default main loop was::
370 Executing that import statement would automatically load the GLib main
371 loop and make this the default. This is now deprecated, since it's
372 highly non-obvious, but may be useful if you want to write or understand
373 backwards-compatible code.
378 FIXME: describe how to use the Qt event loop too (requires recent pyqt)
380 Making asynchronous calls
381 -------------------------
383 To make a call asynchronous, pass two callables as keyword arguments
384 ``reply_handler`` and ``error_handler`` to the proxy method. The proxy
385 method will immediately return `None`. At some later time, when the event
386 loop is running, one of these will happen: either
388 * the ``reply_handler`` will be called with the method's return values
391 * the ``error_handler`` will be called with one argument, an instance of
392 ``DBusException`` representing a remote exception.
397 ``examples/example-async-client.py`` makes asynchronous method calls to
398 the service provided by ``examples/example-service.py`` which return
399 either a value or an exception. As for ``examples/example-client.py``,
400 you need to run ``examples/example-service.py`` in the background or
401 in another shell first.
403 .. --------------------------------------------------------------------
408 To receive signals, the Bus needs to be connected to an event loop - see
409 section `Setting up an event loop`_. Signals will only be received while
410 the event loop is running.
415 To respond to signals, you can use the ``add_signal_receiver`` method on
416 `Bus objects`_. This arranges for a callback to be called when a
417 matching signal is received, and has the following arguments:
419 * a callable (the ``handler_function``) which will be called by the event loop
420 when the signal is received - its parameters will be the arguments of
423 * the signal name, ``signal_name``: here None (the default) matches all names
425 * the D-Bus interface, ``dbus_interface``: again None is the default,
426 and matches all interfaces
428 * a sender bus name (well-known or unique), ``bus_name``: None is again
429 the default, and matches all senders. Well-known names match signals
430 from whatever application is currently the primary owner of that
433 * a sender object path, ``path``: once again None is the default and
434 matches all object paths
436 ``add_signal_receiver`` also has keyword arguments ``utf8_strings`` and
437 ``byte_arrays`` which influence the types used when calling the
438 handler function, in the same way as the `byte_arrays and utf8_strings`_
439 options on proxy methods.
441 ``add_signal_receiver`` returns a ``SignalMatch`` object. Its only
442 useful public API at the moment is a ``remove`` method with no
443 arguments, which removes the signal match from the connection.
445 Getting more information from a signal
446 --------------------------------------
448 You can also arrange for more information to be passed to the handler
449 function. If you pass the keyword arguments ``sender_keyword``,
450 ``destination_keyword``, ``interface_keyword``, ``member_keyword`` or
451 ``path_keyword`` to the ``connect_to_signal`` method, the appropriate
452 part of the signal message will be passed to the handler function as a
453 keyword argument: for instance if you use ::
455 def handler(sender=None):
456 print "got signal from %r" % sender
458 iface.connect_to_signal("Hello", handler, sender_keyword='sender')
460 and a signal ``Hello`` with no arguments is received from
461 ``com.example.Foo``, the ``handler`` function will be called with
462 ``sender='com.example.Foo'``.
464 String argument matching
465 ------------------------
467 If there are keyword parameters for the form ``arg``\ *n* where n is a
468 small non-negative number, their values must be ``unicode`` objects
469 or UTF-8 strings. The handler will only be called if that argument
470 of the signal (numbered from zero) is a D-Bus string (in particular,
471 not an object-path or a signature) with that value.
473 .. *this comment is to stop the above breaking vim syntax highlighting*
475 Receiving signals from a proxy object
476 -------------------------------------
478 `Proxy objects`_ have a special method ``connect_to_signal`` which
479 arranges for a callback to be called when a signal is received
480 from the corresponding remote object. The parameters are:
482 * the name of the signal
484 * a callable (the handler function) which will be called by the event loop
485 when the signal is received - its parameters will be the arguments of
488 * the handler function, a callable: the same as for ``add_signal_receiver``
490 * the keyword argument ``dbus_interface`` qualifies the name with its
493 `dbus.Interface` objects have a similar ``connect_to_signal`` method,
494 but in this case you don't need the ``dbus_interface`` keyword argument
495 since the interface to use is already known.
497 The same extra keyword arguments as for ``add_signal_receiver`` are also
498 available, and just like ``add_signal_receiver``, it returns a
501 You shouldn't use proxy objects just to listen to signals, since they
502 might activate the relevant service when created, but if you already have a
503 proxy object in order to call methods, it's often convenient to use it to add
509 ``examples/signal-recipient.py`` receives signals - it demonstrates
510 general signal matching as well as ``connect_to_signal``. Before running it,
511 you'll need to run ``examples/signal-emitter.py`` in the background or
516 .. --------------------------------------------------------------------
521 FIXME describe `BusName`_ - perhaps fix its API first?
523 The unique-instance idiom
524 -------------------------
526 FIXME provide exemplary code, put it in examples
529 .. _exported objects:
531 .. --------------------------------------------------------------------
536 Objects made available to other applications over D-Bus are said to be
537 *exported*. All subclasses of ``dbus.service.Object`` are automatically
540 To export objects, the Bus needs to be connected to an event loop - see
541 section `Setting up an event loop`_. Exported methods will only be called,
542 and queued signals will only be sent, while the event loop is running.
544 .. _dbus.service.Object:
546 Inheriting from ``dbus.service.Object``
547 ---------------------------------------
549 To export an object onto the Bus, just subclass
550 ``dbus.service.Object``. Object expects either a `BusName`_ or a `Bus
551 object`_, and an object-path, to be passed to its constructor: arrange
552 for this information to be available. For example::
554 class Example(dbus.service.Object):
555 def __init__(self, object_path):
556 dbus.service.Object.__init__(self, dbus.SessionBus(), path)
558 This object will automatically support introspection, but won't do
559 anything particularly interesting. To fix that, you'll need to export some
560 methods and signals too.
562 FIXME also mention dbus.gobject.ExportedGObject once I've written it
564 Exporting methods with ``dbus.service.method``
565 ----------------------------------------------
567 To export a method, use the decorator ``dbus.service.method``. For
570 class Example(dbus.service.Object):
571 def __init__(self, object_path):
572 dbus.service.Object.__init__(self, dbus.SessionBus(), path)
574 @dbus.service.method(dbus_interface='com.example.Sample',
575 in_signature='v', out_signature='s')
576 def StringifyVariant(self, variant):
579 The ``in_signature`` and ``out_signature`` are D-Bus signature strings
580 as described in `Data Types`_.
582 As well as the keywords shown, you can pass ``utf8_strings`` and
583 ``byte_arrays`` keyword arguments, which influence the types which will
584 be passed to the decorated method when it's called via D-Bus, in the
585 same way that the `byte_arrays and utf8_strings`_ options affect the
586 return value of a proxy method.
588 You can find a simple example in ``examples/example-service.py``, which
589 we used earlier to demonstrate ``examples/example-client.py``.
591 Finding out the caller's bus name
592 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
594 The ``method`` decorator accepts a ``sender_keyword`` keyword argument.
595 If you set that to a string, the unique bus name of the sender will be
596 passed to the decorated method as a keyword argument of that name::
598 class Example(dbus.service.Object):
599 def __init__(self, object_path):
600 dbus.service.Object.__init__(self, dbus.SessionBus(), path)
602 @dbus.service.method(dbus_interface='com.example.Sample',
603 in_signature='', out_signature='s',
604 sender_keyword='sender')
605 def SayHello(self, sender=None):
606 return 'Hello, %s!' % sender
607 # -> something like 'Hello, :1.1!'
609 Asynchronous method implementations
610 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
612 FIXME and also add an example, perhaps examples/example-async-service.py
614 Emitting signals with ``dbus.service.signal``
615 ---------------------------------------------
617 To export a signal, use the decorator ``dbus.service.signal``; to emit
618 that signal, call the decorated method. The decorated method can also
619 contain code which will be run when called, as usual. For example::
621 class Example(dbus.service.Object):
622 def __init__(self, object_path):
623 dbus.service.Object.__init__(self, dbus.SessionBus(), path)
625 @dbus.service.signal(dbus_interface='com.example.Sample',
627 def NumberOfBottlesChanged(self, number, contents):
628 print "%d bottles of %s on the wall" % (number, contents)
630 e = Example('/bottle-counter')
631 e.NumberOfBottlesChanged(100, 'beer')
632 # -> emits com.example.Sample.NumberOfBottlesChanged(100, 'beer')
633 # and prints "100 bottles of beer on the wall"
635 The signal will be queued for sending when the decorated method returns -
636 you can prevent the signal from being sent by raising an exception
637 from the decorated method (for instance, if the parameters are
638 inappropriate). The signal will only actually be sent when the event loop
644 ``examples/example-signal-emitter.py`` emits some signals on demand when
645 one of its methods is called. (In reality, you'd emit a signal when some
646 sort of internal state changed, which may or may not be triggered by a
649 .. --------------------------------------------------------------------
651 License for this document
652 =========================
654 Copyright 2006-2007 `Collabora Ltd.`_
656 Licensed under the Academic Free License version 2.1
658 This document is free software; you can redistribute it and/or modify
659 it under the terms of the GNU Lesser General Public License as published by
660 the Free Software Foundation; either version 2.1 of the License, or
661 (at your option) any later version.
663 This document is distributed in the hope that it will be useful,
664 but WITHOUT ANY WARRANTY; without even the implied warranty of
665 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
666 GNU Lesser General Public License for more details.
668 You should have received a copy of the GNU Lesser General Public License
669 along with this document; if not, write to the Free Software
670 Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
673 vim:set ft=rst sw=4 sts=4 et tw=72: