Scroll to navigation

PYTHON-SDBUS(1) python-sdbus PYTHON-SDBUS(1)

NAME

python-sdbus - python-sdbus

Python-sdbus is the python D-Bus library that aim to use the modern features of python

  • Asyncio
  • Type hints
  • Based on fast sd-bus
  • Unified client/server interface classes. Write interface class once.
  • D-Bus methods can have keyword and default arguments.

D-BUS

D-Bus is the inter-process communication standard commonly used on Linux desktop.

This documentation expects you to be familiar with D-Bus concepts and conventions.

If you are unfamiliar with D-Bus you might want to read following pages:

Wikipedia page

Lennart Poettering post about D-Bus

D-Bus specification by freedesktop.org

Install D-Spy D-Bus debugger and observe services and objects on your D-Bus

General Information

Blocking vs Async

Python-sdbus supports both blocking and async IO.

Regular python functions are always blocking.

Asyncio is a part of python standard library that allows non-blocking io.

Asyncio documentation

Generally blocking IO should only be used for simple scripts and programs that interact with existing D-Bus objects.

Blocking:

  • Blocking is easier to initiate (no event loop)
  • Properties behave exactly as Python properties do. (i.e. can assign with '=' operator)
  • Only allows one request at a time.
  • No D-Bus signals.
  • Cannot serve objects, only interact with existing object on D-Bus.

Blocking quick start

Blocking API

Asyncio:

  • Calls need to be await ed.
  • Multiple requests at the same time.
  • Serve object on D-Bus for other programs.
  • D-Bus Signals.

Asyncio quick start

Asyncio API

D-Bus types conversion

D-Bus types reference

NOTE:

Python integers are unlimited size but D-Bus integers are not. All integer types raise OverflowError if you try to pass number outside the type size.

Unsigned integers range is 0 < (2**bit_size)-1.

Signed integers range is -(2**(bit_size-1)) < (2**(bit_size-1))-1.



Name D-Bus type Python type Description
Boolean b bool True or False
Byte y int Unsigned 8-bit integer. Note: array of bytes (ay) has different type in python domain.
Int16 n int Signed 16-bit integer.
Uint16 q int Unsigned 16-bit integer.
Int32 i int Signed 32-bit integer.
Uint32 u int Unsigned 32-bit integer.
Int64 x int Signed 64-bit integer.
Uint64 t int Unsigned 64-bit integer.
Double d float Float point number
Unix FD h int File descriptor
String s str String
Object Path o str Syntactically correct D-Bus object path
Signature g str D-Bus type signature
Array a list List of some single type. Example: as array of strings
Byte Array ay bytes Array of bytes. Not a unique type in D-Bus but a different type in Python. Accepts both bytes and bytearray. Used for binary data.
Struct () tuple Tuple. Example: (isax) tuple of int, string and array of int.
Dictionary a{} dict Dictionary with key type and value type. Note: Dictionary is always a part of array. I.E. a{si} is the dict with string keys and integer values. {si} is NOT a valid signature.
Variant v tuple Unknown type that can be any single type. In Python represented by a tuple of a signature string and a single type. Example: ("s", "test") variant of a single string

Name conversions

D-Bus uses CamelCase for method names.

Python uses snake_case.

When decorating a method name will be automatically translated from snake_case to CamelCase. Example: close_notification -> CloseNotification

However, all decorators have a parameter to force D-Bus name to a specific value. See API documentation for a particular decorator.

Default bus

Most object methods that take a bus as a parameter will use a thread-local default bus connection if a bus object is not explicitly passed.

Session bus is default bus when running as a user and system bus otherwise.

The request_default_bus_name_async and request_default_bus_name can be used to acquire a service name on the default bus.

Use sd_bus_open_user() and sd_bus_open_system() to acquire a specific bus connection.

The set_default_bus can be used to set the new thread-local bus. This should be done before any objects that take bus as an init argument are created. If no bus has been set the new bus will be initialized and set as thread-local default.

The bus can also be set as default for the current context using set_context_default_bus. The context refers to the standard library's contextvars module context variables frequently used in asyncio frameworks. Context-local default bus has higher priority over thread-local default bus.

Glossary

  • Bus object representing connection to D-Bus.
Without proxy you manipulate messages directly.

  • Remote something that exists outside current Python process.
  • Local something that exists inside current Python scope.
For example, systemd acquires org.freedesktop.systemd1 name.

Signature D-Bus type definition. Represented by a string. See D-Bus types conversion.

Contents

  • Index
  • API Index
  • Search Page

Common API

These calls are shared between async and blocking API.

Default bus

Get default bus.

Returns context-local default bus if set or thread-local otherwise.

If no default bus is set initializes a new bus using sdbus.sd_bus_open() and sets it as a thread-local default bus.


Set thread-local default bus.

Should be called before creating any objects that will use default bus.

Default bus can be replaced but the change will only affect newly created objects.


Set context-local default bus.

Should be called before creating any objects that will use default bus.

Default bus can be replaced but the change will only affect newly created objects.

Context-local default bus has higher priority over thread-local one but has to be explicitly set.

Token that can be used to reset context bus back. See contextvars documentation for details.


Asynchronously acquire a name on the default bus.
  • new_name -- Name to acquire. Must be a valid D-Bus service name.
  • allow_replacement -- If name was acquired allow other D-Bus peers to take away the name.
  • replace_existing -- If current name owner allows, take away the name.
  • queue -- Queue up for name acquisition. SdBusRequestNameInQueueError will be raised when successfully placed in queue. Ownership change signal should be monitored get notified when the name was acquired.

Name request exceptions and other D-Bus exceptions.


Acquire a name on the default bus.

Blocks until a reply is received from D-Bus daemon.

  • new_name -- Name to acquire. Must be a valid D-Bus service name.
  • allow_replacement -- If name was acquired allow other D-Bus peers to take away the name.
  • replace_existing -- If current name owner allows, take away the name.
  • queue -- Queue up for name acquisition. SdBusRequestNameInQueueError will be raised when successfully placed in queue. Ownership change signal should be monitored get notified when the name was acquired.

Name request exceptions and other D-Bus exceptions.


D-Bus connections calls

Opens a new bus connection. The session bus will be opened when available or system bus otherwise.
Session or system bus.
SdBus


Opens a new user session bus connection.
Session bus.
SdBus


Opens a new system bus connection.
System bus.
SdBus


Opens a new system bus connection on a remote host through SSH. Host can be prefixed with username@ and followed by :port and /machine_name as in systemd-nspawn container name.
host (str) -- Host name to connect.
Remote system bus.
SdBus


Opens a new system bus connection in a systemd-nspawn container. Machine name can be prefixed with username@. Special machine name .host indicates local system.
machine (str) -- Machine (container) name.
Remote system bus.
SdBus


Opens a new user session bus connection in a systemd-nspawn container. Opens root user bus session or can be prefixed with username@ for a specific user.
machine (str) -- Machine (container) name.
Remote system bus.
SdBus


Helper functions

Encode that arbitrary string as a valid object path prefixed with prefix.
  • prefix (str) -- Prefix path. Must be a valid object path.
  • external (str) -- Arbitrary string to identify object.

valid object path
str

Example on how systemd encodes unit names on D-Bus:

from sdbus import encode_object_path
# System uses /org/freedesktop/systemd1/unit as prefix of all units
# dbus.service is a name of D-Bus unit but dot . is not a valid object path
s = encode_object_path('/org/freedesktop/systemd1/unit', 'dbus.service')
print(s)
# Prints: /org/freedesktop/systemd1/unit/dbus_2eservice



Decode object name that was encoded with encode_object_path().
  • prefix (str) -- Prefix path. Must be a valid object path.
  • full_path (str) -- Full path to be decoded.

Arbitrary name
str

Example decoding systemd unit name:

from sdbus import decode_object_path
s = decode_object_path(

'/org/freedesktop/systemd1/unit',
'/org/freedesktop/systemd1/unit/dbus_2eservice' ) print(s) # Prints: dbus.service



Flags

Flags are int values that should be ORed to combine.

Example, DbusDeprecatedFlag plus DbusHiddenFlag: DbusDeprecatedFlag | DbusHiddenFlag

Mark this method or property as deprecated in introspection data.

Method or property will not show up in introspection data.

Mark this method or property as unprivileged. This means anyone can call it. Only works for system bus as user session bus is fully trusted by default.

This method does not have a reply message. It instantly returns and does not have any errors.

Mark that this property does not change during object life time.

This property emits signal when it changes.

This property emits signal when it invalidates. (means the value changed but does not include new value in the signal)

This property is too heavy to calculate so its not included in GetAll method call.

Data in messages in sensitive and will be scrubbed from memory after message is red.

Blocking quick start

Interface classes

Python-sdbus works by declaring interface classes.

Interface classes for blocking IO should be derived from DbusInterfaceCommon.

The class constructor takes interface_name keyword to determine the D-Bus interface name for all D-Bus elements declared in the class body.

Example:

class ExampleInterface(DbusInterfaceCommon,

interface_name='org.example.myinterface'
):
...


Interface class body should contain the definitions of methods and properties using the decorators dbus_method() and dbus_property() respectively.

Example:

from sdbus import (DbusInterfaceCommon,

dbus_method, dbus_property) class ExampleInterface(DbusInterfaceCommon,
interface_name='org.example.myinterface'
):
# Method that takes an integer and does not return anything
@dbus_method('u')
def close_notification(self, an_int: int) -> None:
raise NotImplementedError
# Read only property of int
@dbus_property()
def test_int(self) -> int:
raise NotImplementedError


This is an interface of that defines a one D-Bus method and one property.

The actual body of the decorated function will not be called. Instead the call will be routed through D-Bus to a another process. Interface can have non-decorated functions that will act as regular methods.

Blocking IO can only interact with existing D-Bus objects and can not be served for other processes to interact with. See Blocking vs Async

Initiating proxy

DbusInterfaceCommon.__init__() method takes service_name and object_path of the remote object that the object will proxy to.

Example creating a proxy and calling method:

...
# Initialize the object
d = ExampleInterface(

service_name='org.example.test',
object_path='/', ) d.close_notification(1234)


NOTE:

Successfully initiating a proxy object does NOT guarantee that the D-Bus object exists.


Methods

Methods are functions wrapped with dbus_method() decorator.

If the remote object sends an error reply an exception with base of DbusFailedError will be raised. See Exceptions for list of exceptions.

The wrapped function will not be called. Its recommended to set the function to raise NotImplementedError.

Example:

from sdbus import DbusInterfaceCommon, dbus_method
class ExampleInterface(...):

...
# Body of some class
@dbus_method('u')
def close_notification(self, an_int: int) -> None:
raise NotImplementedError


Properties

D-Bus property is defined by wrapping a function with dbus_property() decorator.

Example:

from sdbus import DbusInterfaceCommon, dbus_property
class ExampleInterface(...):

...
# Body of some class
# Property of str
@dbus_property('s')
def test_string(self) -> str:
raise NotImplementedError


The new property behaves very similar to Pythons property() decorator.

# Initialize the proxy
d = ExampleInterface(

service_name='org.example.test',
object_path='/', ) # Print it print(d.test_string) # Assign new string d.test_string = 'some_string'


If property is read-only when DbusPropertyReadOnlyError will be raised.

Multiple interfaces

A D-Bus object can have multiple interfaces with different methods and properties.

To implement this define multiple interface classes and do a multiple inheritance on all interfaces the object has.

Example:

from sdbus import DbusInterfaceCommon, dbus_method
class ExampleInterface(DbusInterfaceCommon,

interface_name='org.example.myinterface'
):
@dbus_method('i')
def example_method(self, an_int: int) -> None:
raise NotImplementedError class TestInterface(DbusInterfaceCommon,
interface_name='org.example.test'
):
@dbus_method('as')
def test_method(self, str_array: list[str]) -> None:
raise NotImplementedError class MultipleInterfaces(TestInterface, ExampleInterface):
...


MultipleInterfaces class will have both test_method and example_method that will be proxied to correct interface names. (org.example.myinterface and org.example.test respectively)

Blocking API

Classes

D-Bus interface class. D-Bus methods and properties should be defined using dbus_property() and dbus_method() decorators.
interface_name (str) -- Sets the D-Bus interface name that will be used for all properties and methods defined in the body of the class

__init__(service_name, object_path[, bus])
Init will create a proxy to a remote object
  • service_name (str) -- Remote object D-Bus connection name. For example, systemd uses org.freedesktop.systemd1
  • object_path (str) -- Remote object D-Bus path. Should be a forward slash separated path. Starting object is usually /. Example: /org/freedesktop/systemd/unit/dbus_2eservice
  • bus (SdBus) -- Optional D-Bus connection object. If not passed the default D-Bus will be used.



Pings the remote service using D-Bus.

Useful to test if connection or remote service is alive.

WARNING:

This method is ignores the particular object path meaning it can NOT be used to test if object exist.



Returns the machine UUID of D-Bus the object is connected to.
machine UUID
str


Get D-Bus introspection XML.

It is users responsibility to parse that data.

string with introspection XML
str


Get all object properties as a dictionary where keys are member names and values are properties values.

Equivalent to GetAll method of the org.freedesktop.DBus.Properties interface but the member names are automatically translated to python names. (internally calls it for each interface used in class definition)

on_unknown_member (str) -- If an unknown D-Bus property was encountered either raise an "error" (default), "ignore" the property or "reuse" the D-Bus name for the member.
dictionary of properties
dict[str, Any]


Example:

from sdbus import (DbusInterfaceCommon,

dbus_method, dbus_property) class ExampleInterface(DbusInterfaceCommon,
interface_name='org.example.my'
):
# Method that takes an integer and does not return anything
@dbus_method('u')
def close_notification(self, an_int: int) -> None:
raise NotImplementedError
# Method that does not take any arguments and returns a list of str
@dbus_method()
def get_capabilities(self) -> list[str]:
raise NotImplementedError
# Method that takes a dict of {str: str} and returns an int
@dbus_method('a{ss}')
def count_entries(self, a_dict: dict[str, str]) -> int:
raise NotImplementedError
# Read only property of int
@dbus_property()
def test_int(self) -> int:
raise NotImplementedError
# Read/Write property of str
@dbus_property('s')
def test_string(self) -> str:
raise NotImplementedError



This class is almost identical to DbusInterfaceCommon but implements ObjectManager interface.
Get the objects this object manager in managing.
Triple nested dictionary that contains all the objects paths with their properties values.

dict[ObjectPath, dict[InterfaceName, dict[PropertyName, PropertyValue]]]

dict[str, dict[str, dict[str, Any]]]



Decorators

@sdbus.dbus_method([input_signature[, flags[, method_name]]])
Define D-Bus method

Decorated function becomes linked to D-Bus method. Always use round brackets () even when not passing any arguments.

  • input_signature (str) -- D-Bus input signature. Defaults to "" meaning method takes no arguments. Required if method takes any arguments.
  • flags (int) --

    modifies behavior. No effect on remote connections. Defaults to 0 meaning no special behavior.

    See Flags .

  • method_name (str) -- Explicitly define remote method name. Usually not required as remote method name will be constructed based on original method name.


Defining methods example:

from sdbus import DbusInterfaceCommon, dbus_method
class ExampleInterface(DbusInterfaceCommon,

interface_name='org.example.my'
):
# Method that takes an integer and does not return anything
@dbus_method('u')
def close_notification(self, an_int: int) -> None:
raise NotImplementedError
# Method that does not take any arguments and returns a list of str
@dbus_method()
def get_capabilities(self) -> list[str]:
raise NotImplementedError
# Method that takes a dict of {str: str} and returns an int
@dbus_method('a{ss}')
def count_entries(self, a_dict: dict[str, str]) -> int:
raise NotImplementedError


Calling methods example:

# Initialize the object
d = ExampleInterface(

service_name='org.example.test',
object_path='/', ) d.close_notification(1234) l = d.get_capabilities() d.count_entries({'a': 'asdasdasd', 'b': 'hgterghead213d'})



@sdbus.dbus_property([property_signature[, flags[, property_name]]])
Define D-Bus property

Property works just like @property decorator would. Always use round brackets () even when not passing any arguments.

Read only property can be indicated by passing empty D-Bus signature "".

Trying to assign a read only property will raise AttributeError

  • property_signature (str) -- D-Bus property signature. Empty signature "" indicates read-only property. Defaults to empty signature "". Required only for writable properties.
  • flags (int) --

    modifies behavior. No effect on remote connections. Defaults to 0 meaning no special behavior.

    See Flags .

  • property_name (str) -- Explicitly define remote property name. Usually not required as remote property name will be constructed based on original method name.


Defining properties example:

from sdbus import DbusInterfaceCommon, dbus_property
class ExampleInterface(DbusInterfaceCommon,

interface_name='org.example.myproperty'
):
# Property of int
@dbus_property('i')
def test_int(self) -> int:
raise NotImplementedError
# Property of str
@dbus_property('s')
def test_string(self) -> str:
raise NotImplementedError


Properties usage example:

# Initialize the object
d = ExampleInterface(

service_name='org.example.test',
object_path='/', ) # Print the int print(d.test_int) # Assign new string d.test_string = 'some_string' # Print it print(d.test_string)



  • Index
  • Module Index
  • Search Page

Asyncio quick start

Interface classes

Python-sdbus works by declaring interface classes.

Interface classes for async IO should be derived from DbusInterfaceCommonAsync.

The class constructor takes interface_name keyword to determine the D-Bus interface name for all D-Bus elements declared in the class body.

Example:

from sdbus import DbusInterfaceCommonAsync
class ExampleInterface(DbusInterfaceCommonAsync,

interface_name='org.example.myinterface'
):
...


Interface class body should contain the definitions of methods, properties and signals using decorators such as dbus_method_async(), dbus_property_async() and dbus_signal_async().

Example:

from sdbus import (DbusInterfaceCommonAsync, dbus_method_async,

dbus_property_async, dbus_signal_async) class ExampleInterface(DbusInterfaceCommonAsync,
interface_name='org.example.myinterface'
):
# Method that takes an integer and multiplies it by 2
@dbus_method_async('i', 'i')
async def double_int(self, an_int: int) -> None:
return an_int * 2
# Read only property of str
@dbus_property_async('s')
def read_string(self) -> int:
return 'Test'
# Signal with a list of strings
@dbus_signal_async('as')
def str_signal(self) -> list[str]:
raise NotImplementedError


Initiating proxy

DbusInterfaceCommonAsync provides two methods for proxying remote objects.

DbusInterfaceCommonAsync.new_proxy() class method bypasses the class __init__ and returns proxy object.

DbusInterfaceCommonAsync._proxify() should be used inside the __init__ methods if your class is a proxy only.

Recommended to create proxy classes that a subclass of the interface:

from sdbus import DbusInterfaceCommonAsync
class ExampleInterface(...):

# Some interface class
... class ExampleClient(ExampleInterface):
def __init__(self) -> None:
# Your client init can proxy to any object based on passed arguments.
self._proxify('org.example.test', '/')


NOTE:

Successfully initiating a proxy object does NOT guarantee that the D-Bus object exists.


Serving objects

DbusInterfaceCommonAsync.export_to_dbus() method will export the object to the D-Bus. After calling it the object becomes visible on D-Bus for other processes to call.

Example using ExampleInterface from before:

from sdbus import request_default_bus_name_async
loop = get_event_loop()
i = ExampleInterface()
async def start() -> None:

# Acquire a name on the bus
await request_default_bus_name_async('org.example.test')
# Start serving at / path
i.export_to_dbus('/') loop.run_until_complete(start()) loop.run_forever()


Connection transparency

The interface objects are designed to be transparent to their connection status. This means if the object not proxied to remote the calls to decorated methods will still work in the local scope.

This is the call to local object:

i = ExampleInterface()
async def test() -> None:

print(await i.double_int(5)) # Will print 10


This is a call to remote object at 'org.example.test' service name and '/' path:

i = ExampleInterface.new_proxy('org.example.test', '/')
async def test() -> None:

print(await i.double_int(5)) # Will print 10


Methods

Methods are async function calls wrapped with dbus_method_async() decorator. (see the API reference for decorator parameters)

Methods have to be async function, otherwise AssertionError will be raised.

While method calls are async there is a inherit timeout timer for any method call.

To return an error to caller you need to raise exception which has a DbusFailedError as base. Regular exceptions will not propagate.

See Exceptions.

Example:

from sdbus import DbusInterfaceCommonAsync, dbus_method_async
class ExampleInterface(...):

...
# Body of some class
# Method that takes a string
# and returns uppercase of that string
@dbus_method_async(
input_signature='s',
result_signature='s',
result_args_names=('uppercased', ) # This is optional but
# makes arguments have names in
# introspection data.
)
async def upper(self, str_to_up: str) -> str:
return str_to_up.upper()


Methods behave exact same way as Python methods would:

print(await example_object.upper('test'))  # prints TEST


Properties

Properties are a single value that can be read and write.

To declare a read only property you need to decorate a regular function with dbus_property_async() decorator.

Example:

from sdbus import DbusInterfaceCommonAsync, dbus_property_async
class ExampleInterface(...):

...
# Body of some class
# Read only property. No setter defined.
@dbus_property_async('i')
def read_only_number(self) -> int:
return 10


To create a read/write property you need to decorate the setter function with the setter attribute of your getter function.

Example:

from sdbus import DbusInterfaceCommonAsync, dbus_property_async
class ExampleInterface(...):

...
# Body of some class
# Read/write property. First define getter.
@dbus_property_async('s')
def read_write_str(self) -> str:
return self.s
# Now create setter. Method name does not matter.
@read_write_str.setter # Use the property setter method as decorator
def read_write_str_setter(self, new_str: str) -> None:
self.s = new_str


Properties are supposed to be lightweight. Make sure you don't block event loop with getter or setter.

Async properties do not behave the same way as property() decorator does.

To get the value of the property you can either directly await on property or use get_async() method. (also need to be awaited)

To set property use set_async() method.

Example:

...
# Somewhere in async function
# Assume we have example_object of class defined above
print(await example_object.read_write_str)  # Print the value of read_write_str
...
# Set read_write_str to new value
await example_object.read_write_str.set_async('test')


Signals

To define a D-Bus signal wrap a function with dbus_signal_async() decorator.

The function is only used for type hints information. It is recommended to just put raise NotImplementedError in to the body of the function.

Example:

from sdbus import DbusInterfaceCommonAsync, dbus_signal_async
class ExampleInterface(...):

...
# Body of some class
@dbus_signal_async('s')
def name_changed(self) -> str:
raise NotImplementedError


To catch a signal use async for loop:

async for x in example_object.name_changed:

print(x)


WARNING:

If you are creating an asyncio task to listen on signals make sure to bind it to a variable and keep it referenced otherwise garbage collector will destroy your task.


A signal can be emitted with emit method.

Example:

example_object.name_changed.emit('test')


Signals can also be caught from multiple D-Bus objects using catch_anywhere method. The async iterator will yield the path of the object that emitted the signal and the signal data.

catch_anywhere can be called from class but in such case the service name must be provided.

Example:

async for path, x in ExampleInterface.name_changed.catch_anywhere('org.example.test'):

print(f"On {path} caught: {x}")


Subclass Overrides

If you define a subclass which overrides a declared D-Bus method or property you need to use dbus_method_async_override() and dbus_property_async_override() decorators. Overridden property can decorate a new setter.

Overridden methods should take same number and type of arguments.

Example:

from sdbus import (dbus_method_async_override,

dbus_property_async_override) # Some subclass class SubclassInterface(...):
...
@dbus_method_async_override()
async def upper(self, str_to_up: str) -> str:
return 'Upper: ' + str_to_up.upper()
@dbus_property_async_override()
def str_prop(self) -> str:
return 'Test property' + self.s
# Setter needs to be decorated again to override
@str_prop.setter
def str_prop_setter(self, new_s: str) -> None:
self.s = new_s.upper()


Multiple interfaces

A D-Bus object can have multiple interfaces with different methods and properties.

To implement this define multiple interface classes and do a multiple inheritance on all interfaces the object has.

Example:

from sdbus import DbusInterfaceCommonAsync
class ExampleInterface(DbusInterfaceCommonAsync,

interface_name='org.example.myinterface'
):
@dbus_method_async('i', 'i')
async def double_int(self, an_int: int) -> None:
return an_int * 2 class TestInterface(DbusInterfaceCommonAsync,
interface_name='org.example.test'
):
@dbus_method_async('as', 's')
async def join_str(self, str_array: list[str]) -> str:
return ''.join(str_array) class MultipleInterfaces(TestInterface, ExampleInterface):
...


MultipleInterfaces class will have both test_method and example_method that will be wired to correct interface names. (org.example.myinterface and org.example.test respectively)

Asyncio API

Classes

D-Bus async interface class. D-Bus methods and properties should be defined using dbus_property_async(), dbus_signal_async(), and dbus_method_async() decorators.

NOTE:

Don't forget to call super().__init__() in derived classes init calls as it sets up important attributes.


  • interface_name (str) -- Sets the D-Bus interface name that will be used for all properties, methods and signals defined in the body of the class.
  • serving_enabled (bool) -- If set to True the interface will not be served on D-Bus. Mostly used for interfaces that sd-bus already provides such as org.freedesktop.DBus.Peer.


Pings the remote service using D-Bus.

Useful to test if connection or remote service is alive.

WARNING:

This method is ignores the particular object path meaning it can NOT be used to test if object exist.



Returns the machine UUID of D-Bus the object is connected to.
machine UUID
str


Get D-Bus introspection XML.

It is users responsibility to parse that data.

string with introspection XML
str


Get all object properties as a dictionary where keys are member names and values are properties values.

Equivalent to GetAll method of the org.freedesktop.DBus.Properties interface but the member names are automatically translated to python names. (internally calls it for each interface used in class definition)

on_unknown_member (str) -- If an unknown D-Bus property was encountered either raise an "error" (default), "ignore" the property or "reuse" the D-Bus name for the member.
dictionary of properties
dict[str, Any]


Signal when one of the objects properties changes.

sdbus.utils.parse.parse_properties_changed() can be used to transform this signal data in to an easier to work with dictionary.

Signal data is:

str Name of the interface where property changed
dict[str, tuple[str, Any]] Dictionary there keys are names of properties changed and values are variants of new value.
list[str] List of property names changed but no new value had been provided


_proxify(bus, service_name, object_path)
Begin proxying to a remote D-Bus object.
  • service_name (str) -- Remote object D-Bus connection name. For example, systemd uses org.freedesktop.systemd1
  • object_path (str) -- Remote object D-Bus path. Should be a forward slash separated path. Starting object is usually /. Example: /org/freedesktop/systemd/unit/dbus_2eservice
  • bus (SdBus) -- Optional D-Bus connection object. If not passed the default D-Bus will be used.



Create new proxy object and bypass __init__.
  • service_name (str) -- Remote object D-Bus connection name. For example, systemd uses org.freedesktop.systemd1
  • object_path (str) -- Remote object D-Bus path. Should be a forward slash separated path. Starting object is usually /. Example: /org/freedesktop/systemd/unit/dbus_2eservice
  • bus (SdBus) -- Optional D-Bus connection object. If not passed the default D-Bus will be used.



Object will appear and become callable on D-Bus.

Returns a handle that can either be used as a context manager to remove the object from D-Bus or .stop() method of the handle can be called to remove object from D-Bus.

Returns a handle that can be used to remove object from D-Bus by either using it as a context manager or by calling .stop() method of the handle.

with dbus_object.export_to_dbus("/"):

# dbus_object can be called from D-Bus inside this
# with block.
... ... handle = dbus_object2.export_to_dbus("/") # dbus_object2 can be called from D-Bus between these statements handle.stop() ... dbus_object3.export_to_dbus("/") # dbus_object3 can be called from D-Bus until all references are # dropped. del dbus_object3


If the handle is discarded the object will remain exported until it gets deallocated.

Changed in version 0.12.0: Added a handle return.

  • object_path (str) -- Object path that it will be available at.
  • bus (SdBus) -- Optional D-Bus connection object. If not passed the default D-Bus will be used.

Handle to control the export.



This class is almost identical to DbusInterfaceCommonAsync but implements ObjectManager interface.

Example of serving objects with ObjectManager:

my_object_manager = DbusObjectManagerInterfaceAsync()
my_object_manager.export_to_dbus('/object/manager')
managed_object = DbusInterfaceCommonAsync()
my_object_manager.export_with_manager('/object/manager/example', managed_object)


Get the objects this object manager in managing.

sdbus.utils.parse.parse_get_managed_objects() can be used to make returned data easier to work with.

Triple nested dictionary that contains all the objects paths with their properties values.

dict[ObjectPath, dict[InterfaceName, dict[PropertyName, PropertyValue]]]

dict[str, dict[str, dict[str, Any]]]


Signal when a new object is added or and existing object gains a new interface.

sdbus.utils.parse.parse_interfaces_added() can be used to make signal data easier to work with.

Signal data is:

str Path to object that was added or modified.
dict[str, dict[str, Any]]] dict[InterfaceName, dict[PropertyName, PropertyValue]]


Signal when existing object or and interface of existing object is removed.

sdbus.utils.parse.parse_interfaces_removed() can be used to make signal data easier to work with.

Signal data is:

str Path to object that was removed or modified.
list[str] Interfaces names that were removed.


Export object to D-Bus and emit a signal that it was added.

ObjectManager must be exported first.

Path should be a subpath of where ObjectManager was exported. Example, if ObjectManager exported to /object/manager, the managed object can be exported at /object/manager/test.

ObjectManager will keep the reference to the object.

Returns a handle that can be used to remove object from D-Bus and drop reference to it by either using it as a context manager or by calling .stop() method of the handle. Signal will be emitted once the object is stopped being exported.

manager = DbusObjectManagerInterfaceAsync()
manager.export_to_dbus('/object/manager')
with manager.export_with_manager("/object/manager/example", dbus_object):

# dbus_object can be called from D-Bus inside this
# with block.
... # Removed signal will be emitted once the with block exits ... handle = manager.export_with_manager("/object/manager/example", dbus_object2) # dbus_object2 can be called from D-Bus between these statements handle.stop() # Removed signal will be emitted once the .stop() method is called


If the handle is discarded the object will remain exported until it gets removed from manager with remove_managed_object() and the object gets deallocated.

Changed in version 0.12.0: Added a handle return.

  • object_path (str) -- Object path that it will be available at.
  • object_to_export (DbusInterfaceCommonAsync) -- Object to export to D-Bus.
  • bus (SdBus) -- Optional D-Bus connection object. If not passed the default D-Bus will be used.

RuntimeError -- ObjectManager was not exported.
Handle to control the export.


Emit signal that object was removed.

Releases reference to the object.

CAUTION:

The object will still be accessible over D-Bus until all references to it will be removed.


managed_object (DbusInterfaceCommonAsync) -- Object to remove from ObjectManager.
  • RuntimeError -- ObjectManager was not exported.
  • KeyError -- Passed object is not managed by ObjectManager.




Decorators

@sdbus.dbus_method_async([input_signature[, result_signature[, flags[, result_args_names[, input_args_names[, method_name]]]]]])
Define a method.

Underlying function must be a coroutine function.

  • input_signature (str) -- D-Bus input signature. Defaults to "" meaning method takes no arguments. Required if you intend to connect to a remote object.
  • result_signature (str) -- D-Bus result signature. Defaults to "" meaning method returns empty reply on success. Required if you intend to serve the object.
  • flags (int) --

    modifies behavior. No effect on remote connections. Defaults to 0 meaning no special behavior.

    See Flags .

  • result_args_names (Sequence[str]) --

    sequence of result argument names.

    These names will show up in introspection data but otherwise have no effect.

    Sequence can be list, tuple, etc... Number of elements in the sequence should match the number of result arguments otherwise SdBusLibraryError will be raised.

    Defaults to result arguments being nameless.

  • input_args_names (Sequence[str]) --

    sequence of input argument names.

    These names will show up in introspection data but otherwise have no effect.

    Sequence can be list, tuple, etc... Number of elements in the sequence should match the number of result arguments otherwise RuntimeError will be raised.

    If result_args_names has been passed when Python function argument names will be used otherwise input arguments will be nameless

  • method_name (str) -- Force specific D-Bus method name instead of being based on Python function name.


Example:

from sdbus import DbusInterfaceCommonAsync, dbus_method_async
class ExampleInterface(DbusInterfaceCommonAsync,

interface_name='org.example.test'
):
# Method that takes a string
# and returns uppercase of that string
@dbus_method_async(
input_signature='s',
result_signature='s',
result_args_names=('uppercased', ) # This is optional but
# makes arguments have names in
# introspection data.
)
async def upper(self, str_to_up: str) -> str:
return str_to_up.upper()



@sdbus.dbus_property_async(property_signature[, flags[, property_name]])
Declare a D-Bus property.

The underlying function has to be a regular def function.

The property will be read-only or read/write based on if setter was declared.

WARNING:

Properties are supposed to be lightweight to get or set. Make sure property getter or setter does not perform heavy IO or computation as that will block other methods or properties.


  • property_signature (str) -- Property D-Bus signature. Has to be a single type or container.
  • flags (int) --

    modifies behavior. No effect on remote connections. Defaults to 0 meaning no special behavior.

    See Flags .

  • property_name (str) -- Force specific property name instead of constructing it based on Python function name.


Example:

from sdbus import DbusInterfaceCommonAsync, dbus_property_async
class ExampleInterface(DbusInterfaceCommonAsync,

interface_name='org.example.test'
):
def __init__(self) -> None:
# This is just a generic init
self.i = 12345
self.s = 'test'
# Read only property. No setter defined.
@dbus_property_async('i')
def read_only_number(self) -> int:
return self.i
# Read/write property. First define getter.
@dbus_property_async('s')
def read_write_str(self) -> str:
return self.s
# Now create setter. Method name does not matter.
@read_write_str.setter # Use the property setter method as decorator
def read_write_str_setter(self, new_str: str) -> None:
self.s = new_str


Properties have following methods:
@setter(set_function)
Defines the setter function. This makes the property read/write instead of read-only.

See example on how to use.


@setter_private(set_function)
Defines the private setter function. The setter can be called locally but property will be read-only from D-Bus.

Calling the setter locally will emit properties_changed signal to D-Bus.

Changed in version 0.12.0: can now be used in overrides.


Get the property value.

The property can also be directly await ed instead of calling this method.


Set property value.



@sdbus.dbus_signal_async([signal_signature[, signal_args_names[, flags[, signal_name]]]])
Defines a D-Bus signal.

Underlying function return type hint is used for signal type hints.

  • signal_signature (str) -- signal D-Bus signature. Defaults to empty signal.
  • signal_args_names (Sequence[str]) --

    sequence of signal argument names.

    These names will show up in introspection data but otherwise have no effect.

    Sequence can be list, tuple, etc... Number of elements in the sequence should match the number of result arguments otherwise RuntimeError will be raised.

    Defaults to result arguments being nameless.

  • flags (int) --

    modifies behavior. No effect on remote connections. Defaults to 0 meaning no special behavior.

    See Flags .

  • signal_name (str) -- Forces specific signal name instead of being based on Python function name.


Example:

from sdbus import DbusInterfaceCommonAsync, dbus_signal_async
class ExampleInterface(DbusInterfaceCommonAsync,

interface_name='org.example.signal'
):
@dbus_signal_async('s')
def name_changed(self) -> str:
raise NotImplementedError


Signals have following methods:
Catch D-Bus signals using the async generator for loop: async for x in something.some_signal.catch():

This is main way to await for new events.

Both remote and local objects operate the same way.

Signal objects can also be async iterated directly: async for x in something.some_signal


Catch signal independent of path. Yields tuple of path of the object that emitted signal and signal data.

async for path, data in something.some_signal.catch_anywhere():

This method can be called from both an proxy object and class. However, it cannot be called on local objects and will raise NotImplementedError.

  • service_name (str) -- Service name of which signals belong to. Required if called from class. When called from proxy object the service name of the proxy will be used.
  • bus (str) -- Optional D-Bus connection object. If not passed when called from proxy the bus connected to proxy will be used or when called from class default bus will be used.



Emit a new signal with args data.



@sdbus.dbus_method_async_override
Override the method.

Method name should match the super class method name that you want to override.

New method should take same arguments.

You must add round brackets to decorator.

Example:

from sdbus import (DbusInterfaceCommonAsync, dbus_method_async

dbus_method_async_override) class ExampleInterface(DbusInterfaceCommonAsync,
interface_name='org.example.test'
):
# Original call
@dbus_method_async('s', 's')
async def upper(self, str_to_up: str) -> str:
return str_to_up.upper() class ExampleOverride(ExampleInterface):
@dbus_method_async_override()
async def upper(self, str_to_up: str) -> str:
return 'Upper: ' + str_to_up.upper()



@sdbus.dbus_property_async_override
Override property.

You must add round brackets to decorator.

Example:

from sdbus import (DbusInterfaceCommonAsync, dbus_property_async

dbus_property_async_override) class ExampleInterface(DbusInterfaceCommonAsync,
interface_name='org.example.test'
):
def __init__(self) -> None:
self.s = 'aaaaaaaaa'
# Original property
@dbus_property_async('s')
def str_prop(self) -> str:
return self.s
@str_prop.setter
def str_prop_setter(self, new_s: str) -> None:
self.s = new_s class ExampleOverride(ExampleInterface):
@dbus_property_async_override()
def str_prop(self) -> str:
return 'Test property' + self.s
# Setter needs to be decorated again to override
@str_prop.setter
def str_prop_setter(self, new_s: str) -> None:
self.s = new_s.upper()



Asyncio advanced topics

Signals without data

D-Bus allows signals to not carry any data. Such signals have the type signature of "". (empty string)

To emit such signals the emit must be explicitly called with None.

Example of an empty signal:

from asyncio import new_event_loop
from sdbus import DbusInterfaceCommonAsync, dbus_signal_async
class ExampleInterface(

DbusInterfaceCommonAsync,
interface_name="org.example.signal" ):
@dbus_signal_async("")
def name_invalidated(self) -> None:
raise NotImplementedError test_object = ExampleInterface() async def emit_empty_signal() -> None:
test_object.export_to_dbus("/")
test_object.name_invalidated.emit(None) loop = new_event_loop() loop.run_until_complete(emit_empty_signal())


Exceptions

Error name bound exceptions

These exceptions are bound to specific D-Bus error names. For example, DbusFailedError is bound to org.freedesktop.DBus.Error.Failed error name.

This means if the remote object sends an error message with this error name the Python will receive this exception.

When raised in a method callback an error message will be sent back to caller.

See list of error exceptions.

New error bound exceptions

If you want to create a new error bound exception you should subclass it from DbusFailedError and provide a unique dbus_error_name attribute in the exception body definition.

Example:

class DbusExampleError(DbusFailedError):

dbus_error_name = 'org.example.Error'


If dbus_error_name is not unique the ValueError will be raised.

Defining an exception will automatically bind incoming error message to this new exception.

Existing exceptions can be manually binded using map_exception_to_dbus_error() function.

Python built-in exceptions

All Python built-in exceptions are mapped to D-Bus errors.

The D-Bus error name is created by appending org.python.Error. to the exception name.

For example, AssertionError is bound to org.python.Error.AssertionError name.

Functions

Map exception to a D-bus error. Error name must be unique.
  • exception (Type[Exception]) -- Exception to bind.
  • dbus_error_name (str) -- D-Bus error name to bind to.



Other exceptions

Base exceptions for all exceptions defined in sdbus.

Message error that is unmapped.

The exceptions argument is a tuple of error name and error message.


sd-bus library returned error.

Exception message contains line number and the error name.


Name request exceptions

These exceptions will be raise if an error related to ownership of D-Bus names occurs when calling request_default_bus_name_async() or request_default_bus_name().

Common base exception for any name ownership error.

Someone already owns the name but the request has been placed in queue.



Error name exception list

Generic failure exception.

Recommended to subclass to create a new exception.




No service with such name exists.

Probably should only be raised by bus daemon.



No process owns the name you called.

Probably should only be raised by bus daemon.











Socket timeout.

This is different from DbusNoReplyError as here the connection to bus timeout not the remote object not replying.








Generic failure exception.

Recommended to subclass to create a new exception.















Utilities

Parsing utilities

Parse unweildy D-Bus structures in to Python native objects and names. Available under sdbus.utils.parse subpackage.

Parse data from properties_changed signal.

Parses changed properties from a single D-Bus object. The object's interface class must be known in advance and passed as a first argument.

Member names will be translated to python defined names. Invalidated properties will have a value of None.

  • interface -- Takes either D-Bus interface class or its object.
  • properties_changed_data -- Tuple caught from signal.
  • on_unknown_member -- If an unknown D-Bus property was encountered either raise an "error" (default), "ignore" the property or "reuse" the D-Bus name for the member.

Dictionary of changed properties with keys translated to python names. Invalidated properties will have value of None.


Parse data from interfaces_added signal.

Takes the possible interface classes and the signal data. Returns the path of new object, the class of the added object (if it matched one of passed interface classes) and the dictionary of python named properties and their values.

The passed interfaces can be async or blocking, the class or an instantiated object, a single item or an iterable of interfaces.

  • interfaces -- Possible interfaces that were added.
  • interfaces_added_data -- Tuple caught from signal.
  • on_unknown_interface -- If an unknown D-Bus interface was encountered either raise an "error" (default) or return "none" instead of interface class.
  • on_unknown_member -- If an unknown D-Bus property was encountered either raise an "error" (default), "ignore" the property or "reuse" the D-Bus name for the member.
  • use_interface_subsets -- Use the subset of interfaces as a valid match. For example, the class that implements org.example.foo would be matched with an data consising of both org.example.foo and org.example.bar. The classes implementing more interfaces will have higher priority over the ones implementing fewer.

Path of new added object, object's class (or None) and dictionary of python translated members and their values.


Parse data from interfaces_added signal.

Takes the possible interface classes and the signal data. Returns the path and the matched class of removed object. (if it matched one of passed interface classes)

The passed interfaces can be async or blocking, the class or an instantiated object, a single item or an iterable of interfaces.

  • interfaces -- Possible interfaces that were removed.
  • interfaces_added_data -- Tuple caught from signal.
  • on_unknown_member -- If an unknown D-Bus interface was encountered either raise an "error" (default) or return "none" instead of interface class.
  • use_interface_subsets -- Use the subset of interfaces as a valid match. For example, the class that implements org.example.foo would be matched with an data consising of both org.example.foo and org.example.bar. The classes implementing more interfaces will have higher priority over the ones implementing fewer.

Path of removed object and object's class (or None).


Parse data from get_managed_objects call.

Takes the possible interface classes and the method's returned data. Returns a dictionary where keys a paths of the managed objects and value is a tuple of class of the object and dictionary of its python named properties and their values.

The passed interfaces can be async or blocking, the class or an instantiated object, a single item or an iterable of interfaces.

  • interfaces -- Possible interfaces of the managed objects.
  • managed_objects_data -- Data returned by get_managed_objects call.
  • on_unknown_interface -- If an unknown D-Bus interface was encountered either raise an "error" (default) or return "none" instead of interface class.
  • on_unknown_member -- If an unknown D-Bus property was encountered either raise an "error" (default), "ignore" the property or "reuse" the D-Bus name for the member.
  • use_interface_subsets -- Use the subset of interfaces as a valid match. For example, the class that implements org.example.foo would be matched with an data consising of both org.example.foo and org.example.bar. The classes implementing more interfaces will have higher priority over the ones implementing fewer.

Dictionary where keys are paths and values are tuples of managed objects classes and their properties data.

New in version 0.12.0.


Inspect utilities

Inspect D-Bus objects and retrieve their D-Bus related attributes such as D-Bus object paths and etc... Available under sdbus.utils.inspect subpackage.

Return the D-Bus path of an object.

If called on a D-Bus proxy returns path of the proxied object.

If called on a local D-Bus object returns the exported D-Bus path. If object is not exported raises LookupError.

If called on an object that is unrelated to D-Bus raises TypeError.

The object's path is inspected in the context of the given bus and if the object is attached to a different bus the LookupError will be raised. If the bus argument is not given or is None the default bus will be checked against.

  • obj -- Object to inspect.
  • bus -- Bus to inspect against. If not given or is None the default bus will be used.

D-Bus path of the object.

New in version 0.13.0.


Examples

Asyncio client and server

In this example we create a simple example server and client.

There are 3 files:

  • example_interface.py File that contains the interface definition.
  • example_server.py Server.
  • example_client.py Client.

example_interface.py file:

from sdbus import (DbusInterfaceCommonAsync, dbus_method_async,

dbus_property_async, dbus_signal_async) # This is file only contains interface definition for easy import # in server and client files class ExampleInterface(
DbusInterfaceCommonAsync,
interface_name='org.example.interface' ):
@dbus_method_async(
input_signature='s',
result_signature='s',
)
async def upper(self, string: str) -> str:
return string.upper()
@dbus_property_async(
property_signature='s',
)
def hello_world(self) -> str:
return 'Hello, World!'
@dbus_signal_async(
signal_signature='i'
)
def clock(self) -> int:
raise NotImplementedError


example_server.py file:

from asyncio import get_event_loop, sleep
from random import randint
from time import time
from example_interface import ExampleInterface
from sdbus import request_default_bus_name_async
loop = get_event_loop()
export_object = ExampleInterface()
async def clock() -> None:

"""
This coroutine will sleep a random time and emit a signal with current clock
"""
while True:
await sleep(randint(2, 7)) # Sleep a random time
current_time = int(time()) # The interface we defined uses integers
export_object.clock.emit(current_time) async def startup() -> None:
"""Perform async startup actions"""
# Acquire a known name on the bus
# Clients will use that name to address to this server
await request_default_bus_name_async('org.example.test')
# Export the object to D-Bus
export_object.export_to_dbus('/') loop.run_until_complete(startup()) task_clock = loop.create_task(clock()) loop.run_forever()


example_client.py file:

from asyncio import get_event_loop
from example_interface import ExampleInterface
# Create a new proxy object
example_object = ExampleInterface.new_proxy('org.example.test', '/')
async def print_clock() -> None:

# Use async for loop to print clock signals we receive
async for x in example_object.clock:
print('Got clock: ', x) async def call_upper() -> None:
s = 'test string'
s_after = await example_object.upper(s)
print('Initial string: ', s)
print('After call: ', s_after) async def get_hello_world() -> None:
print('Remote property: ', await example_object.hello_world) loop = get_event_loop() # Always binds your tasks to a variable task_upper = loop.create_task(call_upper()) task_clock = loop.create_task(print_clock()) task_hello_world = loop.create_task(get_hello_world()) loop.run_forever()


Start server before client. python example_server.py

In separated terminal start client. python example_client.py

Use CTRL-C to close client and server.

You can also use ExampleInterface as a local object:

from asyncio import run
from example_interface import ExampleInterface
example_object = ExampleInterface()
async def test() -> None:

print(await example_object.upper('test'))
print(await example_object.hello_world) run(test())


Interfaces repository

python-sdbus includes two namespace packages sdbus_async and sdbus_block which are used for proxies.

For example, D-Bus daemon interface (which comes by default) can be found under sdbus_async.dbus_daemon for async binds and sdbus_block.dbus_daemon for blocking binds.

Known proxies

D-Bus daemon interface

D-Bus daemon.

This is the D-Bus daemon interface. Used for querying D-Bus state.

D-Bus interface object path and service name is predetermined. (at 'org.freedesktop.DBus', '/org/freedesktop/DBus')

bus (SdBus) -- Optional D-Bus connection. If not passed the default D-Bus will be used.

D-Bus Method

Get process ID that owns a specified name.

service_name (str) -- Service name to query.
PID of name owner
DbusNameHasNoOwnerError -- Nobody owns that name


D-Bus Method

Get process user ID that owns a specified name.

service_name (str) -- Service name to query.
User ID of name owner
DbusNameHasNoOwnerError -- Nobody owns that name


D-Bus Method

Returns machine id where bus is run. (stored in /etc/machine-id)

Machine id


D-Bus Method

Returns unique bus name (i.e. ':1.94') for given service name.

service_name (str) -- Service name to query.
Unique bus name.
DbusNameHasNoOwnerError -- Nobody owns that name


D-Bus Method

Lists all activatable services names.

List of all names.


D-Bus Method

List all services and connections currently of the bus.

List of all current names.


D-Bus Method

Return True if someone already owns the name, False if nobody does.

service_name (str) -- Service name to query.
Is the name owned?


D-Bus Method

Starts a specified service.

Flags parameter is not used currently and should be omitted or set to 0.

  • service_name (str) -- Service name to start.
  • flags (int) -- Not used. Omit or pass 0.

1 on success, 2 if already started.


D-Bus property

Python type: list[str]

D-Bus type: as

List of D-Bus daemon features.

Features include:

  • 'AppArmor' - Messages filtered by AppArmor on this bus.
  • 'HeaderFiltering' - Messages are filtered if they have incorrect header fields.
  • 'SELinux' - Messages filtered by SELinux on this bus.
  • 'SystemdActivation' - services activated by systemd if their .service file specifies a D-Bus name.


D-Bus property

Python type: list[str]

D-Bus type: as

Extra D-Bus daemon interfaces


D-Bus signal

Python type: str

D-Bus type: s

Signal when current process acquires a bus name.


D-Bus signal

Python type: str

D-Bus type: s

Signal when current process loses a bus name.


D-Bus signal

Python type: tuple[str, str, str]

D-Bus type: sss

Signal when some name on a bus changes owner.

Is a tuple of:

  • The name that acquired or lost
  • Old owner (by unique bus name) or empty string if no one owned it
  • New owner (by unique bus name) or empty string if no one owns it now



This list contains the known python-sdbus interface collections:

  • D-Bus daemon interface. Built-in.
  • Notifications.
  • NetworkManager.
  • Secrets.

Interface code generator

Python-sdbus is able to generate the interfaces code from the D-Bus introspection XML. (either from a file or live object on D-Bus) Currently async interfaces code is generated by default. Blocking interfaces can be generated by passing --block option.

Running code generator requires Jinja to be installed.

WARNING:

Do NOT send the generator result to exec() function. Interface code MUST be inspected before running.


The generated interfaces code will be syntactically correct but NOT stylistically. It is recommended running a code formatter on the generated code. (for example black)

Generating from XML files

To run generator on files (such as found under /usr/share/dbus-1/interfaces/ folder) execute the sdbus module with gen-from-file first argument and file paths to introspection XML files:

python -m sdbus gen-from-file /usr/share/dbus-1/interfaces/org.gnome.Shell.Screenshot.xml


The generated interface code will be printed in to stdout. You can use shell redirection > to save it in to file.

Multiple interface files can be passed which generates a file containing multiple interfaces.

Generating from run-time introspection

To run generator on some service on the D-Bus execute the sdbus module with gen-from-connection first argument, the service connection name as second and one or more object paths:

python -m sdbus gen-from-connection org.freedesktop.systemd1 /org/freedesktop/systemd1


The generated interface code will be printed in to stdout. You can use shell redirection > to save it in to file.

Multiple object paths can be passed which generates a file containing all interfaces encountered in the objects.

Pass --system option to use system bus instead of session bus.

Renaming interfaces and members

New in version 0.13.0.

Some interface and member names might conflict with Python keywords when converted from D-Bus introspection to Python code by gerator. The CLI interface allow to override the particular interface and member names using the --select-* and --set-name options. The selector options move the cursor to a particular interface and member

Available override options:

Sets the name of currently selected element as it would be in generated Python code. Can be used if either interface or member is selected.

Selects the interface using its D-Bus name.

Selects the method using its D-Bus name. An interface must be selected first.

Selects the property using its D-Bus name. An interface must be selected first.

Selects the signal using its D-Bus name. An interface must be selected first.


For example, an org.example.Interface interface has a property called Class. When automatically converted the name will become class which is a reserved Python keyword.

Using these CLI options it is possible to override the name of the property and class:

python -m sdbus gen-from-file \

org.example.interface.xml \
--select-interface org.example.Interface \
--set-name Example \
--select-property Class \
--set-name example_class


This will generate following Python code:

class Example:

@dbus_property_async(
property_signature="s",
)
def example_class(self) -> str:
raise NotImplementedError


Autodoc extensions

Python-sdbus has an extension for Sphinx autodoc that can document D-Bus interfaces.

To use it include "sdbus.autodoc" extension in your conf.py file.

extensions = ['sdbus.autodoc']


The extension can document interface class bodies. For example, python-sdbus-networkmanager uses it to document the classes.

.. autoclass:: sdbus_async.networkmanager.NetworkManagerDeviceBluetoothInterfaceAsync

:members:


WARNING:

Autodoc extension is early in development and has multiple issues. For example, the inheritance :inherited-members: does not work on the D-Bus elements.


Writing docstrings

The D-Bus methods should be documented same way as the regular function would. See Sphinx documentation on possible fields

Example docstring for a D-Bus method:

@dbus_method_async('s', method_name='GetConnectionUnixProcessID')
async def get_connection_pid(self, service_name: str) -> int:

"""Get process ID that owns a specified name.
:param service_name: Service name to query.
:return: PID of name owner
:raises DbusNameHasNoOwnerError: Nobody owns that name
"""
raise NotImplementedError


D-Bus properties and signals will be annotated with type taken from the stub function.

@dbus_property_async('as')
def features(self) -> list[str]:

"""List of D-Bus daemon features.
Features include:
* 'AppArmor' - Messages filtered by AppArmor on this bus.
* 'HeaderFiltering' - Messages are filtered if they have incorrect \
header fields.
* 'SELinux' - Messages filtered by SELinux on this bus.
* 'SystemdActivation' - services activated by systemd if their \
.service file specifies a D-Bus name.
"""
raise NotImplementedError


No parameters are supported at the moment for properties and signals.

Unit testing

Python-sdbus provides several utilities to enable unit testing.

Extension of unittest.IsolatedAsyncioTestCase from standard library.

Creates an isolated instance of session D-Bus. The D-Bus will be closed and cleaned up after tests are finished.

Requires dbus-daemon executable be installed.

Example:

from sdbus import DbusInterfaceCommonAsync, dbus_method_async
from sdbus.unittest import IsolatedDbusTestCase
class TestInterface(DbusInterfaceCommonAsync,

interface_name='org.test.test',
):
@dbus_method_async("s", "s")
async def upper(self, string: str) -> str:
"""Uppercase the input"""
return string.upper() def initialize_object() -> tuple[TestInterface, TestInterface]:
test_object = TestInterface()
test_object.export_to_dbus('/')
test_object_connection = TestInterface.new_proxy(
"org.example.test", '/')
return test_object, test_object_connection class TestProxy(IsolatedDbusTestCase):
async def asyncSetUp(self) -> None:
await super().asyncSetUp()
await self.bus.request_name_async("org.example.test", 0)
async def test_method_kwargs(self) -> None:
test_object, test_object_connection = initialize_object()
self.assertEqual(
'TEST',
await test_object_connection.upper('test'),
)


Bus instance connected to isolated D-Bus environment.

It is also set as a default bus.


Assert that a given signal was emitted at least once within the given timeout.
  • signal -- D-Bus signal object. Can be a signal from either local or proxy object.
  • timeout (Union[int, float]) -- Maximum wait time until first captured signal.


Should be used as an async context manager. The context manager exits as soon as first signal is captured.

The object returned by context manager has following attributes:

List of captured data.

Example:

async with self.assertDbusSignalEmits(test_object.test_signal) as signal_record:

test_object.test_signal.emit("test") self.assertEqual(["test"], signal_record.output)


New in version 0.12.0.



API Index

Common:

get_default_bus()

request_default_bus_name_async()

set_default_bus()

decode_object_path()

encode_object_path()

sd_bus_open_system()

sd_bus_open_user()

DbusDeprecatedFlag

DbusHiddenFlag

DbusNoReplyFlag

DbusPropertyConstFlag

DbusPropertyEmitsChangeFlag

DbusPropertyEmitsInvalidationFlag

DbusPropertyExplicitFlag

DbusSensitiveFlag

DbusUnprivilegedFlag

Asyncio:

DbusInterfaceCommonAsync

dbus_method_async()

dbus_method_async_override()

dbus_property_async()

dbus_property_async_override()

dbus_signal_async()

Blocking:

DbusInterfaceCommon

dbus_method()

dbus_property()

Exceptions:

exceptions.DbusAccessDeniedError

exceptions.DbusAccessDeniedError

exceptions.DbusAddressInUseError

exceptions.DbusAuthFailedError

exceptions.DbusBadAddressError

exceptions.DbusDisconnectedError

exceptions.DbusFailedError

exceptions.DbusFileExistsError

exceptions.DbusFileNotFoundError

exceptions.DbusInconsistentMessageError

exceptions.DbusInteractiveAuthorizationRequiredError

exceptions.DbusInvalidArgsError

exceptions.DbusInvalidFileContentError

exceptions.DbusInvalidSignatureError

exceptions.DbusIOError

exceptions.DbusLimitsExceededError

exceptions.DbusMatchRuleInvalidError

exceptions.DbusMatchRuleNotFound

exceptions.DbusNameHasNoOwnerError

exceptions.DbusNoMemoryError

exceptions.DbusNoNetworkError

exceptions.DbusNoReplyError

exceptions.DbusNoServerError

exceptions.DbusNotSupportedError

exceptions.DbusPropertyReadOnlyError

exceptions.DbusServiceUnknownError

exceptions.DbusTimeoutError

exceptions.DbusUnixProcessIdUnknownError

exceptions.DbusUnknownInterfaceError

exceptions.DbusUnknownMethodError

exceptions.DbusUnknownObjectError

exceptions.DbusUnknownPropertyError

exceptions.SdBusBaseError

exceptions.SdBusLibraryError

exceptions.SdBusUnmappedMessageError

exceptions.map_exception_to_dbus_error()

exceptions.SdBusRequestNameError

exceptions.SdBusRequestNameInQueueError

exceptions.SdBusRequestNameExistsError

exceptions.SdBusRequestNameAlreadyOwnerError

  • Index
  • API Index
  • Search Page

AUTHOR

igo95862

April 12, 2025