DBusConnection#
Added in version 2.26.
Superclasses: Object
Implemented Interfaces: AsyncInitable, Initable
The GDBusConnection type is used for D-Bus connections to remote
peers such as a message buses.
It is a low-level API that offers a lot of flexibility. For instance,
it lets you establish a connection over any transport that can by represented
as a IOStream.
This class is rarely used directly in D-Bus clients. If you are writing
a D-Bus client, it is often easier to use the bus_own_name,
bus_watch_name or new_for_bus APIs.
As an exception to the usual GLib rule that a particular object must not
be used by two threads at the same time, GDBusConnections methods may be
called from any thread. This is so that bus_get and
bus_get_sync can safely return the same GDBusConnection when
called from any thread.
Most of the ways to obtain a GDBusConnection automatically initialize it
(i.e. connect to D-Bus): for instance, new and
bus_get, and the synchronous versions of those methods, give you
an initialized connection. Language bindings for GIO should use
new or new_async, which also
initialize the connection.
If you construct an uninitialized GDBusConnection, such as via
new, you must initialize it via init or
init_async before using its methods or properties.
Calling methods or accessing properties on a GDBusConnection that has not
completed initialization successfully is considered to be invalid, and leads
to undefined behaviour. In particular, if initialization fails with a
GError, the only valid thing you can do with that GDBusConnection is to
free it with unref.
An example D-Bus server#
Here is an example for a D-Bus server: gdbus-example-server.c
An example for exporting a subtree#
Here is an example for exporting a subtree: gdbus-example-subtree.c
An example for file descriptor passing#
Here is an example for passing UNIX file descriptors: gdbus-unix-fd-client.c
An example for exporting a GObject#
Here is an example for exporting a Object:
gdbus-example-export.c
Constructors#
- class DBusConnection
- classmethod new_finish(res: AsyncResult) DBusConnection#
Finishes an operation started with
new().Added in version 2.26.
- Parameters:
res – a
AsyncResultobtained from theAsyncReadyCallbackpassed tonew().
- classmethod new_for_address_finish(res: AsyncResult) DBusConnection#
Finishes an operation started with
new_for_address().Added in version 2.26.
- Parameters:
res – a
AsyncResultobtained from theAsyncReadyCallbackpassed tonew()
- classmethod new_for_address_sync(address: str, flags: DBusConnectionFlags, observer: DBusAuthObserver | None = None, cancellable: Cancellable | None = None) DBusConnection#
Synchronously connects and sets up a D-Bus client connection for exchanging D-Bus messages with an endpoint specified by
addresswhich must be in the D-Bus address format.This constructor can only be used to initiate client-side connections - use
new_sync()if you need to act as the server. In particular,flagscannot contain theAUTHENTICATION_SERVER,AUTHENTICATION_ALLOW_ANONYMOUSorAUTHENTICATION_REQUIRE_SAME_USERflags.This is a synchronous failable constructor. See
new_for_address()for the asynchronous version.If
observeris notNoneit may be used to control the authentication process.Added in version 2.26.
- Parameters:
address – a D-Bus address
flags – flags describing how to make the connection
observer – a
DBusAuthObserverorNonecancellable – a
CancellableorNone
- classmethod new_sync(stream: IOStream, guid: str | None, flags: DBusConnectionFlags, observer: DBusAuthObserver | None = None, cancellable: Cancellable | None = None) DBusConnection#
Synchronously sets up a D-Bus connection for exchanging D-Bus messages with the end represented by
stream.If
streamis aSocketConnection, then the correspondingSocketwill be put into non-blocking mode.The D-Bus connection will interact with
streamfrom a worker thread. As a result, the caller should not interact withstreamafter this method has been called, except by callingunref()on it.If
observeris notNoneit may be used to control the authentication process.This is a synchronous failable constructor. See
new()for the asynchronous version.Added in version 2.26.
- Parameters:
stream – a
IOStreamguid – the GUID to use if authenticating as a server or
Noneflags – flags describing how to make the connection
observer – a
DBusAuthObserverorNonecancellable – a
CancellableorNone
Methods#
- class DBusConnection
- add_filter(filter_function: Callable[[DBusConnection, DBusMessage, bool, Any], DBusMessage | None], user_data: Any = None) int#
Adds a message filter. Filters are handlers that are run on all incoming and outgoing messages, prior to standard dispatch. Filters are run in the order that they were added. The same handler can be added as a filter more than once, in which case it will be run more than once. Filters added during a filter callback won’t be run on the message being processed. Filter functions are allowed to modify and even drop messages.
Note that filters are run in a dedicated message handling thread so they can’t block and, generally, can’t do anything but signal a worker thread. Also note that filters are rarely needed - use API such as
send_message_with_reply(),signal_subscribe()orcall()instead.If a filter consumes an incoming message the message is not dispatched anywhere else - not even the standard dispatch machinery (that API such as
signal_subscribe()andsend_message_with_reply()relies on) will see the message. Similarly, if a filter consumes an outgoing message, the message will not be sent to the other peer.If
user_data_free_funcis non-None, it will be called (in the thread-default main context of the thread you are calling this method from) at some point afteruser_datais no longer needed. (It is not guaranteed to be called synchronously when the filter is removed, and may be called afterconnectionhas been destroyed.)Added in version 2.26.
- Parameters:
filter_function – a filter function
user_data – user data to pass to
filter_function
- async call(self, bus_name: str | None, object_path: str, interface_name: str, method_name: str, parameters: Variant | None, reply_type: VariantType | None, flags: DBusCallFlags, timeout_msec: int) Variant#
This is the awaitable version of
call().Added in version 2.26.
- Parameters:
bus_name – a unique or well-known bus name or
Noneifconnectionis not a message bus connectionobject_path – path of remote object
interface_name – D-Bus interface to invoke method on
method_name – the name of the method to invoke
parameters – a
Varianttuple with parameters for the method orNoneif not passing parametersreply_type – the expected type of the reply (which will be a tuple), or
Noneflags – flags from the
DBusCallFlagsenumerationtimeout_msec – the timeout in milliseconds, -1 to use the default timeout or %G_MAXINT for no timeout
- call(bus_name: str | None, object_path: str, interface_name: str, method_name: str, parameters: Variant | None, reply_type: VariantType | None, flags: DBusCallFlags, timeout_msec: int, cancellable: Cancellable | None = None, callback: Callable[[Object | None, AsyncResult, Any], None] | None = None, user_data: Any = None) None#
Asynchronously invokes the
method_namemethod on theinterface_nameD-Bus interface on the remote object atobject_pathowned bybus_name.If
connectionis closed then the operation will fail withCLOSED. Ifcancellableis canceled, the operation will fail withCANCELLED. Ifparameterscontains a value not compatible with the D-Bus protocol, the operation fails withINVALID_ARGUMENT.If
reply_typeis non-Nonethen the reply will be checked for having this type and an error will be raised if it does not match. Said another way, if you give areply_typethen any non-Nonereturn value will be of this type. Unless it’s %G_VARIANT_TYPE_UNIT, thereply_typewill be a tuple containing one or more values.If the
parametersVariantis floating, it is consumed. This allows convenient ‘inline’ use ofnew(), e.g.:g_dbus_connection_call (connection, "org.freedesktop.StringThings", "/org/freedesktop/StringThings", "org.freedesktop.StringThings", "TwoStrings", g_variant_new ("(ss)", "Thing One", "Thing Two"), NULL, G_DBUS_CALL_FLAGS_NONE, -1, NULL, (GAsyncReadyCallback) two_strings_done, NULL);
This is an asynchronous method. When the operation is finished,
callbackwill be invoked in the [thread-default main context][g-main-context-push-thread-default] of the thread you are calling this method from. You can then callcall_finish()to get the result of the operation. Seecall_sync()for the synchronous version of this function.If
callbackisNonethen the D-Bus method call message will be sent with theNO_REPLY_EXPECTEDflag set.Added in version 2.26.
- Parameters:
bus_name – a unique or well-known bus name or
Noneifconnectionis not a message bus connectionobject_path – path of remote object
interface_name – D-Bus interface to invoke method on
method_name – the name of the method to invoke
parameters – a
Varianttuple with parameters for the method orNoneif not passing parametersreply_type – the expected type of the reply (which will be a tuple), or
Noneflags – flags from the
DBusCallFlagsenumerationtimeout_msec – the timeout in milliseconds, -1 to use the default timeout or %G_MAXINT for no timeout
cancellable – a
CancellableorNonecallback – a
AsyncReadyCallbackto call when the request is satisfied orNoneif you don’t care about the result of the method invocationuser_data – the data to pass to
callback
- call_finish(res: AsyncResult) Variant#
Finishes an operation started with
call().Added in version 2.26.
- Parameters:
res – a
AsyncResultobtained from theAsyncReadyCallbackpassed tocall()
- call_sync(bus_name: str | None, object_path: str, interface_name: str, method_name: str, parameters: Variant | None, reply_type: VariantType | None, flags: DBusCallFlags, timeout_msec: int, cancellable: Cancellable | None = None) Variant#
Synchronously invokes the
method_namemethod on theinterface_nameD-Bus interface on the remote object atobject_pathowned bybus_name.If
connectionis closed then the operation will fail withCLOSED. Ifcancellableis canceled, the operation will fail withCANCELLED. Ifparameterscontains a value not compatible with the D-Bus protocol, the operation fails withINVALID_ARGUMENT.If
reply_typeis non-Nonethen the reply will be checked for having this type and an error will be raised if it does not match. Said another way, if you give areply_typethen any non-Nonereturn value will be of this type.If the
parametersVariantis floating, it is consumed. This allows convenient ‘inline’ use ofnew(), e.g.:g_dbus_connection_call_sync (connection, "org.freedesktop.StringThings", "/org/freedesktop/StringThings", "org.freedesktop.StringThings", "TwoStrings", g_variant_new ("(ss)", "Thing One", "Thing Two"), NULL, G_DBUS_CALL_FLAGS_NONE, -1, NULL, &error);
The calling thread is blocked until a reply is received. See
call()for the asynchronous version of this method.Added in version 2.26.
- Parameters:
bus_name – a unique or well-known bus name or
Noneifconnectionis not a message bus connectionobject_path – path of remote object
interface_name – D-Bus interface to invoke method on
method_name – the name of the method to invoke
parameters – a
Varianttuple with parameters for the method orNoneif not passing parametersreply_type – the expected type of the reply, or
Noneflags – flags from the
DBusCallFlagsenumerationtimeout_msec – the timeout in milliseconds, -1 to use the default timeout or %G_MAXINT for no timeout
cancellable – a
CancellableorNone
- async call_with_unix_fd_list(self, bus_name: str | None, object_path: str, interface_name: str, method_name: str, parameters: Variant | None, reply_type: VariantType | None, flags: DBusCallFlags, timeout_msec: int, fd_list: UnixFDList | None = None) tuple[Variant, UnixFDList]#
This is the awaitable version of
call_with_unix_fd_list().Added in version 2.30.
- Parameters:
bus_name – a unique or well-known bus name or
Noneifconnectionis not a message bus connectionobject_path – path of remote object
interface_name – D-Bus interface to invoke method on
method_name – the name of the method to invoke
parameters – a
Varianttuple with parameters for the method orNoneif not passing parametersreply_type – the expected type of the reply, or
Noneflags – flags from the
DBusCallFlagsenumerationtimeout_msec – the timeout in milliseconds, -1 to use the default timeout or %G_MAXINT for no timeout
fd_list – a
UnixFDListorNone
- call_with_unix_fd_list(bus_name: str | None, object_path: str, interface_name: str, method_name: str, parameters: Variant | None, reply_type: VariantType | None, flags: DBusCallFlags, timeout_msec: int, fd_list: UnixFDList | None = None, cancellable: Cancellable | None = None, callback: Callable[[Object | None, AsyncResult, Any], None] | None = None, user_data: Any = None) None#
Like
call()but also takes aUnixFDListobject.The file descriptors normally correspond to %G_VARIANT_TYPE_HANDLE values in the body of the message. For example, if a message contains two file descriptors,
fd_listwould have length 2, andg_variant_new_handle (0)andg_variant_new_handle (1)would appear somewhere in the body of the message (not necessarily in that order!) to represent the file descriptors at indexes 0 and 1 respectively.When designing D-Bus APIs that are intended to be interoperable, please note that non-GDBus implementations of D-Bus can usually only access file descriptors if they are referenced in this way by a value of type %G_VARIANT_TYPE_HANDLE in the body of the message.
This method is only available on UNIX.
Added in version 2.30.
- Parameters:
bus_name – a unique or well-known bus name or
Noneifconnectionis not a message bus connectionobject_path – path of remote object
interface_name – D-Bus interface to invoke method on
method_name – the name of the method to invoke
parameters – a
Varianttuple with parameters for the method orNoneif not passing parametersreply_type – the expected type of the reply, or
Noneflags – flags from the
DBusCallFlagsenumerationtimeout_msec – the timeout in milliseconds, -1 to use the default timeout or %G_MAXINT for no timeout
fd_list – a
UnixFDListorNonecancellable – a
CancellableorNonecallback – a
AsyncReadyCallbackto call when the request is satisfied orNoneif you don’t * care about the result of the method invocationuser_data – The data to pass to
callback.
- call_with_unix_fd_list_finish(res: AsyncResult) tuple[Variant, UnixFDList]#
Finishes an operation started with
call_with_unix_fd_list().The file descriptors normally correspond to %G_VARIANT_TYPE_HANDLE values in the body of the message. For example, if
get_handle()returns 5, that is intended to be a reference to the file descriptor that can be accessed byg_unix_fd_list_get (*out_fd_list, 5, ...).When designing D-Bus APIs that are intended to be interoperable, please note that non-GDBus implementations of D-Bus can usually only access file descriptors if they are referenced in this way by a value of type %G_VARIANT_TYPE_HANDLE in the body of the message.
Added in version 2.30.
- Parameters:
res – a
AsyncResultobtained from theAsyncReadyCallbackpassed tocall_with_unix_fd_list()
- call_with_unix_fd_list_sync(bus_name: str | None, object_path: str, interface_name: str, method_name: str, parameters: Variant | None, reply_type: VariantType | None, flags: DBusCallFlags, timeout_msec: int, fd_list: UnixFDList | None = None, cancellable: Cancellable | None = None) tuple[Variant, UnixFDList]#
Like
call_sync()but also takes and returnsUnixFDListobjects. Seecall_with_unix_fd_list()andcall_with_unix_fd_list_finish()for more details.This method is only available on UNIX.
Added in version 2.30.
- Parameters:
bus_name – a unique or well-known bus name or
Noneifconnectionis not a message bus connectionobject_path – path of remote object
interface_name – D-Bus interface to invoke method on
method_name – the name of the method to invoke
parameters – a
Varianttuple with parameters for the method orNoneif not passing parametersreply_type – the expected type of the reply, or
Noneflags – flags from the
DBusCallFlagsenumerationtimeout_msec – the timeout in milliseconds, -1 to use the default timeout or %G_MAXINT for no timeout
fd_list – a
UnixFDListorNonecancellable – a
CancellableorNone
- close(cancellable: Cancellable | None = None, callback: Callable[[Object | None, AsyncResult, Any], None] | None = None, user_data: Any = None) None#
Closes
connection. Note that this never causes the process to exit (this might only happen if the other end of a shared message bus connection disconnects, seeDBusConnection:exit-on-close).Once the connection is closed, operations such as sending a message will return with the error
CLOSED. Closing a connection will not automatically flush the connection so queued messages may be lost. Useflush()if you need such guarantees.If
connectionis already closed, this method fails withCLOSED.When
connectionhas been closed, theDBusConnection::closed signal is emitted in the [thread-default main context][g-main-context-push-thread-default] of the thread thatconnectionwas constructed in.This is an asynchronous method. When the operation is finished,
callbackwill be invoked in the [thread-default main context][g-main-context-push-thread-default] of the thread you are calling this method from. You can then callclose_finish()to get the result of the operation. Seeclose_sync()for the synchronous version.Added in version 2.26.
- Parameters:
cancellable – a
CancellableorNonecallback – a
AsyncReadyCallbackto call when the request is satisfied orNoneif you don’t care about the resultuser_data – The data to pass to
callback
- close_finish(res: AsyncResult) bool#
Finishes an operation started with
close().Added in version 2.26.
- Parameters:
res – a
AsyncResultobtained from theAsyncReadyCallbackpassed toclose()
- close_sync(cancellable: Cancellable | None = None) bool#
Synchronously closes
connection. The calling thread is blocked until this is done. Seeclose()for the asynchronous version of this method and more details about what it does.Added in version 2.26.
- Parameters:
cancellable – a
CancellableorNone
- emit_signal(destination_bus_name: str | None, object_path: str, interface_name: str, signal_name: str, parameters: Variant | None = None) bool#
Emits a signal.
If the parameters GVariant is floating, it is consumed.
This can only fail if
parametersis not compatible with the D-Bus protocol (INVALID_ARGUMENT), or ifconnectionhas been closed (CLOSED).Added in version 2.26.
- Parameters:
destination_bus_name – the unique bus name for the destination for the signal or
Noneto emit to all listenersobject_path – path of remote object
interface_name – D-Bus interface to emit a signal on
signal_name – the name of the signal to emit
parameters – a
Varianttuple with parameters for the signal orNoneif not passing parameters
- export_action_group(object_path: str, action_group: ActionGroup) int#
Exports
action_grouponconnectionatobject_path.The implemented D-Bus API should be considered private. It is subject to change in the future.
A given object path can only have one action group exported on it. If this constraint is violated, the export will fail and 0 will be returned (with
errorset accordingly).You can unexport the action group using
unexport_action_groupwith the return value of this function.The thread default main context is taken at the time of this call. All incoming action activations and state change requests are reported from this context. Any changes on the action group that cause it to emit signals must also come from this same context. Since incoming action activations and state change requests are rather likely to cause changes on the action group, this effectively limits a given action group to being exported from only one main context.
Added in version 2.32.
- Parameters:
object_path – a D-Bus object path
action_group – an action group
Exports
menuonconnectionatobject_path.The implemented D-Bus API should be considered private. It is subject to change in the future.
An object path can only have one menu model exported on it. If this constraint is violated, the export will fail and 0 will be returned (with
errorset accordingly).Exporting menus with sections containing more than
MENU_EXPORTER_MAX_SECTION_SIZEitems is not supported and results in undefined behavior.You can unexport the menu model using
unexport_menu_model()with the return value of this function.Added in version 2.32.
- Parameters:
object_path – a D-Bus object path
menu – a
MenuModel
- flush(cancellable: Cancellable | None = None, callback: Callable[[Object | None, AsyncResult, Any], None] | None = None, user_data: Any = None) None#
Asynchronously flushes
connection, that is, writes all queued outgoing message to the transport and then flushes the transport (usingflush_async()). This is useful in programs that wants to emit a D-Bus signal and then exit immediately. Without flushing the connection, there is no guaranteed that the message has been sent to the networking buffers in the OS kernel.This is an asynchronous method. When the operation is finished,
callbackwill be invoked in the [thread-default main context][g-main-context-push-thread-default] of the thread you are calling this method from. You can then callflush_finish()to get the result of the operation. Seeflush_sync()for the synchronous version.Added in version 2.26.
- Parameters:
cancellable – a
CancellableorNonecallback – a
AsyncReadyCallbackto call when the request is satisfied orNoneif you don’t care about the resultuser_data – The data to pass to
callback
- flush_finish(res: AsyncResult) bool#
Finishes an operation started with
flush().Added in version 2.26.
- Parameters:
res – a
AsyncResultobtained from theAsyncReadyCallbackpassed toflush()
- flush_sync(cancellable: Cancellable | None = None) bool#
Synchronously flushes
connection. The calling thread is blocked until this is done. Seeflush()for the asynchronous version of this method and more details about what it does.Added in version 2.26.
- Parameters:
cancellable – a
CancellableorNone
- get_capabilities() DBusCapabilityFlags#
Gets the capabilities negotiated with the remote peer
Added in version 2.26.
- get_exit_on_close() bool#
Gets whether the process is terminated when
connectionis closed by the remote peer. SeeDBusConnection:exit-on-close for more details.Added in version 2.26.
- get_flags() DBusConnectionFlags#
Gets the flags used to construct this connection
Added in version 2.60.
- get_guid() str#
The GUID of the peer performing the role of server when authenticating. See
DBusConnection:guid for more details.Added in version 2.26.
- get_last_serial() int#
Retrieves the last serial number assigned to a
DBusMessageon the current thread. This includes messages sent via both low-level API such assend_message()as well as high-level API such asemit_signal(),call()orcall().Added in version 2.34.
- get_peer_credentials() Credentials | None#
Gets the credentials of the authenticated peer. This will always return
Noneunlessconnectionacted as a server (e.g.AUTHENTICATION_SERVERwas passed) when set up and the client passed credentials as part of the authentication process.In a message bus setup, the message bus is always the server and each application is a client. So this method will always return
Nonefor message bus clients.Added in version 2.26.
- get_stream() IOStream#
Gets the underlying stream used for IO.
While the
DBusConnectionis active, it will interact with this stream from a worker thread, so it is not safe to interact with the stream directly.Added in version 2.26.
- get_unique_name() str | None#
Gets the unique name of
connectionas assigned by the message bus. This can also be used to figure out ifconnectionis a message bus connection.Added in version 2.26.
- classmethod new(guid: str | None, flags: DBusConnectionFlags, observer: DBusAuthObserver | None = None, cancellable: Cancellable | None = None, callback: Callable[[Object | None, AsyncResult, Any], None] | None = None, user_data: Any = None) None#
Asynchronously sets up a D-Bus connection for exchanging D-Bus messages with the end represented by
stream.If
streamis aSocketConnection, then the correspondingSocketwill be put into non-blocking mode.The D-Bus connection will interact with
streamfrom a worker thread. As a result, the caller should not interact withstreamafter this method has been called, except by callingunref()on it.If
observeris notNoneit may be used to control the authentication process.When the operation is finished,
callbackwill be invoked. You can then callnew_finish()to get the result of the operation.This is an asynchronous failable constructor. See
new_sync()for the synchronous version.Added in version 2.26.
- Parameters:
guid – the GUID to use if authenticating as a server or
Noneflags – flags describing how to make the connection
observer – a
DBusAuthObserverorNonecancellable – a
CancellableorNonecallback – a
AsyncReadyCallbackto call when the request is satisfieduser_data – the data to pass to
callback
- classmethod new_for_address(flags: DBusConnectionFlags, observer: DBusAuthObserver | None = None, cancellable: Cancellable | None = None, callback: Callable[[Object | None, AsyncResult, Any], None] | None = None, user_data: Any = None) None#
Asynchronously connects and sets up a D-Bus client connection for exchanging D-Bus messages with an endpoint specified by
addresswhich must be in the D-Bus address format.This constructor can only be used to initiate client-side connections - use
new()if you need to act as the server. In particular,flagscannot contain theAUTHENTICATION_SERVER,AUTHENTICATION_ALLOW_ANONYMOUSorAUTHENTICATION_REQUIRE_SAME_USERflags.When the operation is finished,
callbackwill be invoked. You can then callnew_for_address_finish()to get the result of the operation.If
observeris notNoneit may be used to control the authentication process.This is an asynchronous failable constructor. See
new_for_address_sync()for the synchronous version.Added in version 2.26.
- Parameters:
flags – flags describing how to make the connection
observer – a
DBusAuthObserverorNonecancellable – a
CancellableorNonecallback – a
AsyncReadyCallbackto call when the request is satisfieduser_data – the data to pass to
callback
- register_object(object_path: str, interface_info: DBusInterfaceInfo, method_call_closure: Closure | None = None, get_property_closure: Closure | None = None, set_property_closure: Closure | None = None) int#
Registers callbacks for exported objects at
object_pathwith the D-Bus interface that is described ininterface_info.Calls to functions in
vtable(anduser_data_free_func) will happen in the [thread-default main context][g-main-context-push-thread-default] of the thread you are calling this method from.Note that all
Variantvalues passed to functions invtablewill match the signature given ininterface_info- if a remote caller passes incorrect values, theorg.freedesktop.DBus.Error.InvalidArgsis returned to the remote caller.Additionally, if the remote caller attempts to invoke methods or access properties not mentioned in
interface_infotheorg.freedesktop.DBus.Error.UnknownMethodresp.org.freedesktop.DBus.Error.InvalidArgserrors are returned to the caller.It is considered a programming error if the
DBusInterfaceGetPropertyFuncfunction invtablereturns aVariantof incorrect type.If an existing callback is already registered at
object_pathandinterface_name, thenerroris set toEXISTS.GDBus automatically implements the standard D-Bus interfaces org.freedesktop.DBus.Properties, org.freedesktop.DBus.Introspectable and org.freedesktop.Peer, so you don’t have to implement those for the objects you export. You can implement org.freedesktop.DBus.Properties yourself, e.g. to handle getting and setting of properties asynchronously.
Note that the reference count on
interface_infowill be incremented by 1 (unless allocated statically, e.g. if the reference count is -1, seeref()) for as long as the object is exported. Also note thatvtablewill be copied.See this [server][gdbus-server] for an example of how to use this method.
Added in version 2.26.
- Parameters:
object_path – the object path to register at
interface_info – introspection data for the interface
method_call_closure
get_property_closure
set_property_closure
- register_subtree(object_path: str, vtable: DBusSubtreeVTable, flags: DBusSubtreeFlags, user_data: Any, user_data_free_func: Callable[[Any], None]) int#
Registers a whole subtree of dynamic objects.
The
enumerateandintrospectionfunctions invtableare used to convey, to remote callers, what nodes exist in the subtree rooted byobject_path.When handling remote calls into any node in the subtree, first the
enumeratefunction is used to check if the node exists. If the node exists or theDISPATCH_TO_UNENUMERATED_NODESflag is set theintrospectionfunction is used to check if the node supports the requested method. If so, thedispatchfunction is used to determine where to dispatch the call. The collectedDBusInterfaceVTableandgpointerwill be used to call into the interface vtable for processing the request.All calls into user-provided code will be invoked in the [thread-default main context][g-main-context-push-thread-default] of the thread you are calling this method from.
If an existing subtree is already registered at
object_pathor thenerroris set toEXISTS.Note that it is valid to register regular objects (using
register_object()) in a subtree registered withregister_subtree()- if so, the subtree handler is tried as the last resort. One way to think about a subtree handler is to consider it a fallback handler for object paths not registered viaregister_object()or other bindings.Note that
vtablewill be copied so you cannot change it after registration.See this [server][gdbus-subtree-server] for an example of how to use this method.
Added in version 2.26.
- Parameters:
object_path – the object path to register the subtree at
vtable – a
DBusSubtreeVTableto enumerate, introspect and dispatch nodes in the subtreeflags – flags used to fine tune the behavior of the subtree
user_data – data to pass to functions in
vtableuser_data_free_func – function to call when the subtree is unregistered
- remove_filter(filter_id: int) None#
Removes a filter.
Note that since filters run in a different thread, there is a race condition where it is possible that the filter will be running even after calling
remove_filter(), so you cannot just free data that the filter might be using. Instead, you should pass aDestroyNotifytoadd_filter(), which will be called when it is guaranteed that the data is no longer needed.Added in version 2.26.
- Parameters:
filter_id – an identifier obtained from
add_filter()
- send_message(message: DBusMessage, flags: DBusSendMessageFlags) tuple[bool, int]#
Asynchronously sends
messageto the peer represented byconnection.Unless
flagscontain thePRESERVE_SERIALflag, the serial number will be assigned byconnectionand set onmessageviaset_serial(). Ifout_serialis notNone, then the serial number used will be written to this location prior to submitting the message to the underlying transport. While it has avolatilequalifier, this is a historical artifact and the argument passed to it should not bevolatile.If
connectionis closed then the operation will fail withCLOSED. Ifmessageis not well-formed, the operation fails withINVALID_ARGUMENT.See this [server][gdbus-server] and [client][gdbus-unix-fd-client] for an example of how to use this low-level API to send and receive UNIX file descriptors.
Note that
messagemust be unlocked, unlessflagscontain thePRESERVE_SERIALflag.Added in version 2.26.
- Parameters:
message – a
DBusMessageflags – flags affecting how the message is sent
- send_message_with_reply(message: DBusMessage, flags: DBusSendMessageFlags, timeout_msec: int, cancellable: Cancellable | None = None, callback: Callable[[Object | None, AsyncResult, Any], None] | None = None, user_data: Any = None) int#
Asynchronously sends
messageto the peer represented byconnection.Unless
flagscontain thePRESERVE_SERIALflag, the serial number will be assigned byconnectionand set onmessageviaset_serial(). Ifout_serialis notNone, then the serial number used will be written to this location prior to submitting the message to the underlying transport. While it has avolatilequalifier, this is a historical artifact and the argument passed to it should not bevolatile.If
connectionis closed then the operation will fail withCLOSED. Ifcancellableis canceled, the operation will fail withCANCELLED. Ifmessageis not well-formed, the operation fails withINVALID_ARGUMENT.This is an asynchronous method. When the operation is finished,
callbackwill be invoked in the [thread-default main context][g-main-context-push-thread-default] of the thread you are calling this method from. You can then callsend_message_with_reply_finish()to get the result of the operation. Seesend_message_with_reply_sync()for the synchronous version.Note that
messagemust be unlocked, unlessflagscontain thePRESERVE_SERIALflag.See this [server][gdbus-server] and [client][gdbus-unix-fd-client] for an example of how to use this low-level API to send and receive UNIX file descriptors.
Added in version 2.26.
- Parameters:
message – a
DBusMessageflags – flags affecting how the message is sent
timeout_msec – the timeout in milliseconds, -1 to use the default timeout or %G_MAXINT for no timeout
cancellable – a
CancellableorNonecallback – a
AsyncReadyCallbackto call when the request is satisfied orNoneif you don’t care about the resultuser_data – The data to pass to
callback
- send_message_with_reply_finish(res: AsyncResult) DBusMessage#
Finishes an operation started with
send_message_with_reply().Note that
erroris only set if a local in-process error occurred. That is to say that the returnedDBusMessageobject may be of typeERROR. Useto_gerror()to transcode this to aError.See this [server][gdbus-server] and [client][gdbus-unix-fd-client] for an example of how to use this low-level API to send and receive UNIX file descriptors.
Added in version 2.26.
- Parameters:
res – a
AsyncResultobtained from theAsyncReadyCallbackpassed tosend_message_with_reply()
- send_message_with_reply_sync(message: DBusMessage, flags: DBusSendMessageFlags, timeout_msec: int, cancellable: Cancellable | None = None) tuple[DBusMessage, int]#
Synchronously sends
messageto the peer represented byconnectionand blocks the calling thread until a reply is received or the timeout is reached. Seesend_message_with_reply()for the asynchronous version of this method.Unless
flagscontain thePRESERVE_SERIALflag, the serial number will be assigned byconnectionand set onmessageviaset_serial(). Ifout_serialis notNone, then the serial number used will be written to this location prior to submitting the message to the underlying transport. While it has avolatilequalifier, this is a historical artifact and the argument passed to it should not bevolatile.If
connectionis closed then the operation will fail withCLOSED. Ifcancellableis canceled, the operation will fail withCANCELLED. Ifmessageis not well-formed, the operation fails withINVALID_ARGUMENT.Note that
erroris only set if a local in-process error occurred. That is to say that the returnedDBusMessageobject may be of typeERROR. Useto_gerror()to transcode this to aError.See this [server][gdbus-server] and [client][gdbus-unix-fd-client] for an example of how to use this low-level API to send and receive UNIX file descriptors.
Note that
messagemust be unlocked, unlessflagscontain thePRESERVE_SERIALflag.Added in version 2.26.
- Parameters:
message – a
DBusMessageflags – flags affecting how the message is sent.
timeout_msec – the timeout in milliseconds, -1 to use the default timeout or %G_MAXINT for no timeout
cancellable – a
CancellableorNone
- set_exit_on_close(exit_on_close: bool) None#
Sets whether the process should be terminated when
connectionis closed by the remote peer. SeeDBusConnection:exit-on-close for more details.Note that this function should be used with care. Most modern UNIX desktops tie the notion of a user session with the session bus, and expect all of a user’s applications to quit when their bus connection goes away. If you are setting
exit_on_closetoFalsefor the shared session bus connection, you should make sure that your application exits when the user session ends.Added in version 2.26.
- Parameters:
exit_on_close – whether the process should be terminated when
connectionis closed by the remote peer
- signal_subscribe(sender: str | None, interface_name: str | None, member: str | None, object_path: str | None, arg0: str | None, flags: DBusSignalFlags, callback: Callable[[DBusConnection, str | None, str, str, str, Variant, Any], None], user_data: Any = None) int#
Subscribes to signals on
connectionand invokescallbackwhenever the signal is received. Note thatcallbackwill be invoked in the [thread-default main context][g-main-context-push-thread-default] of the thread you are calling this method from.If
connectionis not a message bus connection,sendermust beNone.If
senderis a well-known name note thatcallbackis invoked with the unique name for the owner ofsender, not the well-known name as one would expect. This is because the message bus rewrites the name. As such, to avoid certain race conditions, users should be tracking the name owner of the well-known name and use that when processing the received signal.If one of
MATCH_ARG0_NAMESPACEorMATCH_ARG0_PATHare given,arg0is interpreted as part of a namespace or path. The first argument of a signal is matched against that part as specified by D-Bus.If
user_data_free_funcis non-None, it will be called (in the thread-default main context of the thread you are calling this method from) at some point afteruser_datais no longer needed. (It is not guaranteed to be called synchronously when the signal is unsubscribed from, and may be called afterconnectionhas been destroyed.)As
callbackis potentially invoked in a different thread from where it’s emitted, it’s possible for this to happen aftersignal_unsubscribe()has been called in another thread. Due to this,user_datashould have a strong reference which is freed withuser_data_free_func, rather than pointing to data whose lifecycle is tied to the signal subscription. For example, if aObjectis used to store the subscription ID fromsignal_subscribe(), a strong reference to thatObjectmust be passed touser_data, andunref()passed touser_data_free_func. You are responsible for breaking the resulting reference count cycle by explicitly unsubscribing from the signal when dropping the last external reference to theObject. Alternatively, a weak reference may be used.It is guaranteed that if you unsubscribe from a signal using
signal_unsubscribe()from the same thread which made the correspondingsignal_subscribe()call,callbackwill not be invoked aftersignal_unsubscribe()returns.The returned subscription identifier is an opaque value which is guaranteed to never be zero.
This function can never fail.
Added in version 2.26.
- Parameters:
sender – sender name to match on (unique or well-known name) or
Noneto listen from all sendersinterface_name – D-Bus interface name to match on or
Noneto match on all interfacesmember – D-Bus signal name to match on or
Noneto match on all signalsobject_path – object path to match on or
Noneto match on all object pathsarg0 – contents of first string argument to match on or
Noneto match on all kinds of argumentsflags –
DBusSignalFlagsdescribing how arg0 is used in subscribing to the signalcallback – callback to invoke when there is a signal matching the requested data
user_data – user data to pass to
callback
- signal_unsubscribe(subscription_id: int) None#
Unsubscribes from signals.
Note that there may still be D-Bus traffic to process (relating to this signal subscription) in the current thread-default
MainContextafter this function has returned. You should continue to iterate theMainContextuntil theDestroyNotifyfunction passed tosignal_subscribe()is called, in order to avoid memory leaks through callbacks queued on theMainContextafter it’s stopped being iterated. Alternatively, any idle source with a priority lower than %G_PRIORITY_DEFAULT that was scheduled after unsubscription, also indicates that all resources of this subscription are released.Added in version 2.26.
- Parameters:
subscription_id – a subscription id obtained from
signal_subscribe()
- start_message_processing() None#
If
connectionwas created withDELAY_MESSAGE_PROCESSING, this method starts processing messages. Does nothing on ifconnectionwasn’t created with this flag or if the method has already been called.Added in version 2.26.
- unexport_action_group(export_id: int) None#
Reverses the effect of a previous call to
export_action_group.It is an error to call this function with an ID that wasn’t returned from
export_action_groupor to call it with the same ID more than once.Added in version 2.32.
- Parameters:
export_id – the ID from
export_action_group
Reverses the effect of a previous call to
export_menu_model().It is an error to call this function with an ID that wasn’t returned from
export_menu_model()or to call it with the same ID more than once.Added in version 2.32.
- Parameters:
export_id – the ID from
export_menu_model()
- unregister_object(registration_id: int) bool#
Unregisters an object.
Added in version 2.26.
- Parameters:
registration_id – a registration id obtained from
register_object()
- unregister_subtree(registration_id: int) bool#
Unregisters a subtree.
Added in version 2.26.
- Parameters:
registration_id – a subtree registration id obtained from
register_subtree()
Properties#
- class DBusConnection
-
- props.authentication_observer: DBusAuthObserver#
The type of the None singleton.
Added in version 2.26.
- props.capabilities: DBusCapabilityFlags#
The type of the None singleton.
Added in version 2.26.
- props.flags: DBusConnectionFlags#
The type of the None singleton.
Added in version 2.26.
Signals#
- class DBusConnection.signals
- closed(remote_peer_vanished: bool, error: GError | None = None) None#
The type of the None singleton.
Added in version 2.26.
- Parameters:
remote_peer_vanished –
Trueifconnectionis closed because the remote peer closed its end of the connectionerror – a
Errorwith more details about the event orNone