Python dbus.Bus Examples


The following are 16 code examples for showing how to use dbus.Bus. They are extracted from open source Python projects. You can click vote to vote up the examples you like, or click vote to vote down the exmaples you don't like. Your votes will be used in our system to extract more high-quality examples.

You may also check out all available functions/classes of the module dbus , or try the search function .


Example 1

From project kupfer-adds, under directory kupfer, in source file keyrelay.py.

Score: 10
vote
vote
def get_all_keys():
	try:
		bus = dbus.Bus()
		obj = bus.get_object(SERV, OBJ)
		iface = dbus.Interface(obj, IFACE)
		return iface.GetBoundKeys(byte_arrays=True)
	except dbus.DBusException as exc:
		print exc
		print "Waiting for Kupfer to start.."
		return []

 

Example 2

From project kupfer-adds, under directory kupfer/plugin, in source file gtg.py.

Score: 10
vote
vote
def initialize(self):
		self.monitor_token = \
			self.monitor_directories(os.path.expanduser(_GTG_HOME))
		bus = dbus.Bus()
		self._signal_new_task = bus.add_signal_receiver(self._on_tasks_updated,
				signal_name="TaskAdded", dbus_interface=_IFACE_NAME2)
		self._signal_task_deleted = bus.add_signal_receiver(self._on_tasks_updated,
				signal_name="TaskDeleted", dbus_interface=_IFACE_NAME2)
		self._signal_task_modified = bus.add_signal_receiver(self._on_tasks_updated,
				signal_name="TaskModified", dbus_interface=_IFACE_NAME2)

	 

Example 3

From project kupfer-adds, under directory kupfer/plugin, in source file gajim.py.

Score: 10
vote
vote
def initialize(self):
		ToplevelGroupingSource.initialize(self)
		# listen to d-bus signals for updates
		signals = [
			"ContactAbsence",
			"ContactPresence",
			"ContactStatus",
			"AccountPresence",
			"Roster",
			"RosterInfo",
		]

		session_bus = dbus.Bus()

		for signal in signals:
			dbus_signal_connect_weakly(session_bus, signal,
					self._signal_update, dbus_interface=_IFACE_NAME)

	 

Example 4

From project kupfer-adds, under directory kupfer/plugin, in source file skype.py.

Score: 10
vote
vote
def __init__(self):
		self._friends = None
		self._authenticated = False
		try:
			self.bus = bus = dbus.Bus()
		except dbus.DBusException, err:
			pretty.print_error(__name__, 'Skype', '__init__', err)
			return

		self._dbus_name_owner_watch = bus.add_signal_receiver(
				self._signal_dbus_name_owner_changed,
				'NameOwnerChanged',
				'org.freedesktop.DBus',
				'org.freedesktop.DBus',
				'/org/freedesktop/DBus',
				arg0=SKYPE_IFACE)

		self._skype_notify_callback = _SkypeNotify(bus, self._signal_update)
		self._signal_dbus_name_owner_changed()

	 

Example 5

From project kupfer-adds, under directory kupfer/plugin, in source file pidgin.py.

Score: 10
vote
vote
def _install_dbus_signal(self):
		'''Add signals to pidgin when buddy goes offline or
		online to update the list'''
		try:
			session_bus = dbus.Bus()
		except dbus.DBusException:
			return

		dbus_signal_connect_weakly(session_bus, "SigningOff",
				self._signing_off, dbus_interface=IFACE_NAME)

		dbus_signal_connect_weakly(session_bus, "BuddySignedOn",
				self._buddy_signed_on, dbus_interface=IFACE_NAME)

		dbus_signal_connect_weakly(session_bus, "BuddyStatusChanged",
				self._buddy_status_changed, dbus_interface=IFACE_NAME)

		dbus_signal_connect_weakly(session_bus, "BuddySignedOff",
				self._buddy_signed_off, dbus_interface=IFACE_NAME)

	 

Example 6

From project telepathy-python, under directory examples, in source file call.py.

Score: 10
vote
vote
def get_stream_engine():
    bus = dbus.Bus()
    return bus.get_object(
        'org.freedesktop.Telepathy.StreamEngine',
        '/org/freedesktop/Telepathy/StreamEngine')

 

Example 7

From project telepathy-python, under directory src/client, in source file connmgr.py.

Score: 10
vote
vote
def __init__(self, service_name, object_path, bus=None):
        if not bus:
            bus = dbus.Bus()

        self.service_name = service_name
        self.object_path = object_path
        object = bus.get_object(service_name, object_path)
        InterfaceFactory.__init__(self, object, CONN_MGR_INTERFACE)

     

Example 8

From project telepathy-python, under directory src/client, in source file conn.py.

Score: 10
vote
vote
def __init__(self, service_name, object_path=None, bus=None,
            ready_handler=None, error_handler=default_error_handler):
        if not bus:
            self.bus = dbus.Bus()
        else:
            self.bus = bus

        if object_path is None:
            object_path = '/' + service_name.replace('.', '/')

        self.service_name = service_name
        self.object_path = object_path
        self._ready_handlers = []
        if ready_handler is not None:
            self._ready_handlers.append(ready_handler)
        self._error_handler = error_handler
        self._ready = False

        object = self.bus.get_object(service_name, object_path)
        InterfaceFactory.__init__(self, object, CONN_INTERFACE)

        # note: old dbus-python returns None from connect_to_signal
        self._status_changed_connection = \
            self[CONN_INTERFACE].connect_to_signal('StatusChanged',
                lambda status, reason: self._status_cb(status))
        self[CONN_INTERFACE].GetStatus(
            reply_handler=self._status_cb,
            error_handler=error_handler)

     

Example 9

From project telepathy-python, under directory src/client, in source file channel.py.

Score: 10
vote
vote
def __init__(self, service_name, object_path, bus=None, ready_handler=None,
                 error_handler=default_error_handler):
        if not bus:
            bus = dbus.Bus()

        self.service_name = service_name
        self.object_path = object_path
        self._ready_handler = ready_handler
        self.error_cb = error_handler
        object = bus.get_object(service_name, object_path)
        InterfaceFactory.__init__(self, object, CHANNEL_INTERFACE)

        if ready_handler:
            self[CHANNEL_INTERFACE].GetChannelType(
                reply_handler=self.get_channel_type_reply_cb,
                error_handler=self.error_cb)
        else:
            type = self.GetChannelType()
            interfaces = self.GetInterfaces()
            self.get_valid_interfaces().add(type)
            self.get_valid_interfaces().update(interfaces)

     

Example 10

From project telepathy-python, under directory src/server, in source file connmgr.py.

Score: 10
vote
vote
def __init__(self, name):
        """
        Initialise the connection manager.
        """
        bus_name = 'org.freedesktop.Telepathy.ConnectionManager.%s' % name
        object_path = '/org/freedesktop/Telepathy/ConnectionManager/%s' % name
        _ConnectionManager.__init__(self,
                                    dbus.service.BusName(bus_name, dbus.Bus(), do_not_queue=True),
                                    object_path)

        self._connections = set()
        self._protos = {}

     

Example 11

From project wazapp, under directory src/client/InterfaceHandlers/DBus, in source file DBusInterfaceHandler.py.

Score: 10
vote
vote
def __init__(self, username):
		bus = dbus.Bus()
		busObj = bus.get_object('com.yowsup.methods', '/com/yowsup/methods')
		
		initMethod = busObj.get_dbus_method("init",'com.yowsup.methods')
		
		result = initMethod(username)
		
		if result:
			self.initSignals(result)
			self.initMethods(result)
		
	 

Example 12

From project dbus-python-egg, under directory test, in source file test-client.py.

Score: 10
vote
vote
def testBusNameCreation(self):
        print '\n******** Testing BusName creation ********'
        test = [('org.freedesktop.DBus.Python.TestName', True),
                ('org.freedesktop.DBus.Python.TestName', True),
                ('org.freedesktop.DBus.Python.InvalidName&^*%$', False)]
        # Do some more intelligent handling/testing of queueing vs success?
        # ('org.freedesktop.DBus.TestSuitePythonService', False)]
        # For some reason this actually succeeds
        # ('org.freedesktop.DBus', False)]

        # make a method call to ensure the test service is active
        self.iface.Echo("foo")

        names = {}
        for (name, succeed) in test:
            try:
                print "requesting %s" % name
                busname = dbus.service.BusName(name, dbus.SessionBus())
            except Exception, e:
                print "%s:\n%s" % (e.__class__, e)
                self.assert_(not succeed, 'did not expect registering bus name %s to fail' % name)
            else:
                print busname
                self.assert_(succeed, 'expected registering bus name %s to fail'% name)
                if name in names:
                    self.assert_(names[name] == busname, 'got a new instance for same name %s' % name)
                    print "instance of %s re-used, good!" % name
                else:
                    names[name] = busname

                del busname

            print

        del names

        bus = dbus.Bus()
        ret = bus.name_has_owner('org.freedesktop.DBus.Python.TestName')
        self.assert_(not ret, 'deleting reference failed to release BusName org.freedesktop.DBus.Python.TestName')

     

Example 13

From project sugar-toolkit, under directory src/sugar/activity, in source file activity.py.

Score: 10
vote
vote
def __init__(self, bundle_id, got_channel_cb):
        self._interfaces = set([CLIENT, CLIENT_HANDLER, PROPERTIES_IFACE])
        self._got_channel_cb = got_channel_cb

        bus = dbus.Bus()
        name = CLIENT + '.' + bundle_id
        bus_name = dbus.service.BusName(name, bus=bus)

        path = '/' + name.replace('.', '/')
        dbus.service.Object.__init__(self, bus_name, path)
        DBusProperties.__init__(self)

        self._implement_property_get(CLIENT, {
            'Interfaces': lambda: list(self._interfaces),
          })
        self._implement_property_get(CLIENT_HANDLER, {
            'HandlerChannelFilter': self.__get_filters_cb,
          })

     

Example 14

From project sugar-toolkit, under directory src/sugar/presence, in source file presenceservice.py.

Score: 10
vote
vote
def get_buddy_by_telepathy_handle(self, tp_conn_name, tp_conn_path,
                                      handle):
        """Retrieve single Buddy object for the given public key

        :Parameters:
            `tp_conn_name` : str
                The well-known bus name of a Telepathy connection
            `tp_conn_path` : dbus.ObjectPath
                The object path of the Telepathy connection
            `handle` : int or long
                The handle of a Telepathy contact on that connection,
                of type HANDLE_TYPE_CONTACT. This may not be a
                channel-specific handle.
        :Returns: the Buddy object, or None if the buddy is not found
        """

        bus = dbus.Bus()
        obj = bus.get_object(ACCOUNT_MANAGER_SERVICE, ACCOUNT_MANAGER_PATH)
        account_manager = dbus.Interface(obj, ACCOUNT_MANAGER)
        account_paths = account_manager.Get(ACCOUNT_MANAGER, 'ValidAccounts',
                                            dbus_interface=PROPERTIES_IFACE)
        for account_path in account_paths:
            obj = bus.get_object(ACCOUNT_MANAGER_SERVICE, account_path)
            connection_path = obj.Get(ACCOUNT, 'Connection')
            if connection_path == tp_conn_path:
                connection_name = connection_path.replace('/', '.')[1:]
                connection = bus.get_object(connection_name, connection_path)
                contact_ids = connection.InspectHandles(HANDLE_TYPE_CONTACT,
                        [handle],
                        dbus_interface=CONNECTION)
                return self.get_buddy(account_path, contact_ids[0])

        raise ValueError('Unknown buddy in connection %s with handle %d',
                         tp_conn_path, handle)

     

Example 15

From project vodafone-mobile-connect, under directory attic/VodafoneMobileConnectCard/output/src/opt/vmc/lib/python2.5/site-packages/dbus, in source file service.py.

Score: 8
vote
vote
def __new__(cls, name, bus=None, allow_replacement=False , replace_existing=False, do_not_queue=False):
        """Constructor, which may either return an existing cached object
        or a new object.

        :Parameters:
            `name` : str
                The well-known name to be advertised
            `bus` : dbus.Bus
                A Bus on which this service will be advertised; if None
                (default) the session bus will be used
            `allow_replacement` : bool
                If True, other processes trying to claim the same well-known
                name will take precedence over this one.
            `replace_existing` : bool
                If True, this process can take over the well-known name
                from other processes already holding it.
            `do_not_queue` : bool
                If True, this service will not be placed in the queue of
                services waiting for the requested name if another service
                already holds it.
        """
        _dbus_bindings.validate_bus_name(name, allow_well_known=True,
                                         allow_unique=False)

        # get default bus
        if bus == None:
            bus = SessionBus()

        # see if this name is already defined, return it if so
        # FIXME: accessing internals of Bus
        if name in bus._bus_names:
            return bus._bus_names[name]

        # otherwise register the name
        name_flags = (
            (allow_replacement and _dbus_bindings.NAME_FLAG_ALLOW_REPLACEMENT or 0) |
            (replace_existing and _dbus_bindings.NAME_FLAG_REPLACE_EXISTING or 0) |
            (do_not_queue and _dbus_bindings.NAME_FLAG_DO_NOT_QUEUE or 0))

        retval = bus.request_name(name, name_flags)

        # TODO: more intelligent tracking of bus name states?
        if retval == _dbus_bindings.REQUEST_NAME_REPLY_PRIMARY_OWNER:
            pass
        elif retval == _dbus_bindings.REQUEST_NAME_REPLY_IN_QUEUE:
            # queueing can happen by default, maybe we should
            # track this better or let the user know if they're
            # queued or not?
            pass
        elif retval == _dbus_bindings.REQUEST_NAME_REPLY_EXISTS:
            raise NameExistsException(name)
        elif retval == _dbus_bindings.REQUEST_NAME_REPLY_ALREADY_OWNER:
            # if this is a shared bus which is being used by someone
            # else in this process, this can happen legitimately
            pass
        else:
            raise RuntimeError('requesting bus name %s returned unexpected value %s' % (name, retval))

        # and create the object
        bus_name = object.__new__(cls)
        bus_name._bus = bus
        bus_name._name = name

        # cache instance (weak ref only)
        # FIXME: accessing Bus internals again
        bus._bus_names[name] = bus_name

        return bus_name

    # do nothing because this is called whether or not the bus name
    # object was retrieved from the cache or created new
     

Example 16

From project hotwire, under directory hotwire/sysdep/ipc_impl, in source file dbusutil.py.

Score: 5
vote
vote
def bus_proxy(bus=None):
    target_bus = bus or dbus.Bus()
    return target_bus.get_object('org.freedesktop.DBus', '/org/freedesktop/DBus')