Python dbus.DBusException() Examples

The following are 30 code examples of dbus.DBusException(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module dbus , or try the search function .
Example #1
Source File: wifi.py    From ideascube with GNU Affero General Public License v3.0 6 votes vote down vote up
def all(cls):
        result = []

        for connection in NMSettings.ListConnections():
            try:
                conn_settings = connection.GetSettings()
            except DBusException as e:
                # NM throws an exception if we try to use GetSettings on a
                # connection owned by another user. We just ignore it.
                continue

            if '802-11-wireless' not in conn_settings:
                continue

            result.append(cls(connection))

        return OrderedDict(
            [(c.ssid, c) for c in sorted(result, key=attrgetter('ssid'))]) 
Example #2
Source File: dbus_connection.py    From rpisurv with GNU General Public License v2.0 6 votes vote down vote up
def VideoPosWrapper(self,args):
        timeout=3
        try:
            # Neither get_object nor start_service_by_name support a timeout. As a workaround you can directly use call_blocking before.
            #This call is just for forcing a shorter timeout then default in case bus is not ready or available
            logger.debug("DBusConnection: start TESTING if bus " + self._dbus_name + " is ready to accept videopos commands")
            self._bus.call_blocking(self._dbus_name, '/org/mpris/MediaPlayer2',
                                    'org.mpris.MediaPlayer2.Player',
                                    'VideoPos',
                                    None, (args), timeout=timeout)

            logger.debug("DBusConnection: bus: " + self._dbus_name + " is ready to accept videopos commands")

            #The previous call_blocking directly is kind of a hack to be able to set the timeout, if this stops working in the future use below to set the VideoPos
            #self.player_interface.VideoPos(args)
        except dbus.DBusException as e:
            logger.debug("DBusConnection: The bus: " + self._dbus_name + " is NOT ready to accept videopos commands: %s", e)

# The python dbus bindings don't provide property access via the
# 'org.freedesktop.DBus.Properties' interface so we wrap the access of
# properties using 
Example #3
Source File: __init__.py    From openrazer with GNU General Public License v2.0 6 votes vote down vote up
def __init__(self):
        # Load up the DBus
        session_bus = _dbus.SessionBus()
        try:
            self._dbus = session_bus.get_object("org.razer", "/org/razer")
        except _dbus.DBusException:
            raise DaemonNotFound("Could not connect to daemon")

        # Get interface for daemon methods
        self._dbus_daemon = _dbus.Interface(self._dbus, "razer.daemon")

        # Get interface for devices methods
        self._dbus_devices = _dbus.Interface(self._dbus, "razer.devices")

        self._device_serials = self._dbus_devices.getDevices()
        self._devices = []

        self._daemon_version = self._dbus_daemon.version()

        for serial in self._device_serials:
            device = _RazerDeviceFactory.get_device(serial)
            self._devices.append(device) 
Example #4
Source File: kwallet.py    From keyring with MIT License 6 votes vote down vote up
def priority(cls):
        if 'dbus' not in globals():
            raise RuntimeError('python-dbus not installed')
        try:
            bus = dbus.SessionBus(mainloop=DBusGMainLoop())
        except dbus.DBusException as exc:
            raise RuntimeError(exc.get_dbus_message())
        try:
            bus.get_object(cls.bus_name, cls.object_path)
        except dbus.DBusException:
            tmpl = 'cannot connect to {bus_name}'
            msg = tmpl.format(bus_name=cls.bus_name)
            raise RuntimeError(msg)
        if "KDE" in os.getenv("XDG_CURRENT_DESKTOP", "").split(":"):
            return 5.1
        return 4.9 
Example #5
Source File: gnome-pass-search-provider.py    From gnome-pass-search-provider with GNU General Public License v3.0 6 votes vote down vote up
def notify(self, message, body="", error=False):
        try:
            self.session_bus.get_object(
                "org.freedesktop.Notifications", "/org/freedesktop/Notifications"
            ).Notify(
                "Pass",
                0,
                "dialog-password",
                message,
                body,
                "",
                {"transient": False if error else True},
                0 if error else 3000,
                dbus_interface="org.freedesktop.Notifications",
            )
        except dbus.DBusException as err:
            print(f"Error {err} while trying to display {message}.") 
Example #6
Source File: gnome-pass-search-provider.py    From gnome-pass-search-provider with GNU General Public License v3.0 6 votes vote down vote up
def send_password_to_clipboard(self, name):
        field = None
        if name.startswith("otp "):
            base_args = ["pass", "otp", "code"]
            name = name[4:]
        else:
            base_args = ["pass", "show"]
            if name.startswith(":"):
                field, name = name.split(" ", 1)
                field = field[1:]

        try:
            self.send_password_to_gpaste(base_args, name, field)
        except dbus.DBusException:
            # We couldn't join GPaste over D-Bus,
            # use pass native clipboard copy
            self.send_password_to_native_clipboard(base_args, name, field) 
Example #7
Source File: gtkapp.py    From autokey with GNU General Public License v3.0 6 votes vote down vote up
def __verifyNotRunning(self):
        if os.path.exists(common.LOCK_FILE):
            pid = Application._read_pid_from_lock_file()

            # Check that the found PID is running and is autokey
            with subprocess.Popen(["ps", "-p", pid, "-o", "command"], stdout=subprocess.PIPE) as p:
                output = p.communicate()[0]

            if "autokey" in output.decode():
                logging.debug("AutoKey is already running as pid %s", pid)
                bus = dbus.SessionBus()

                try:
                    dbusService = bus.get_object("org.autokey.Service", "/AppService")
                    dbusService.show_configure(dbus_interface="org.autokey.Service")
                    sys.exit(0)
                except dbus.DBusException as e:
                    logging.exception("Error communicating with Dbus service")
                    self.show_error_dialog(_("AutoKey is already running as pid %s but is not responding") % pid, str(e))
                    sys.exit(1)

        return True 
Example #8
Source File: hamster.py    From gtg with GNU General Public License v3.0 6 votes vote down vote up
def get_records(self, task):
        """Get a list of hamster facts for a task"""
        ids = self.get_hamster_ids(task)
        records = []
        modified = False
        valid_ids = []
        for i in ids:
            try:
                d = self.hamster.GetFact(i)
                if d and i not in valid_ids:
                    records.append(d)
                    valid_ids.append(i)
                    continue
            except dbus.DBusException:
                pass
            modified = True
            print("Removing invalid fact", i)
        if modified:
            self.set_hamster_ids(task, valid_ids)
        return records 
Example #9
Source File: log.py    From qubes-core-admin with GNU Lesser General Public License v2.1 6 votes vote down vote up
def emit(self, record):
        app_icon = self.app_icons[
            max(level for level in self.app_icons if level <= record.levelno)]

        try:
            # https://developer.gnome.org/notification-spec/#command-notify
            self._notify_object.Notify(
                'Qubes',    # STRING app_name
                0,          # UINT32 replaces_id
                app_icon,   # STRING app_icon
                record.msg, # STRING summary
                '',         # STRING body
                (),         # ARRAY actions
                {},         # DICT hints
                0,          # INT32 timeout
                dbus_interface='org.freedesktop.Notifications')
        except dbus.DBusException:
            pass 
Example #10
Source File: ui.py    From pantalaimon with Apache License 2.0 6 votes vote down vote up
def run(self):
            self.loop = GLib.MainLoop()

            if self.config.notifications:
                try:
                    notify2.init("pantalaimon", mainloop=self.loop)
                    self.notifications = True
                except dbus.DBusException:
                    logger.error(
                        "Notifications are enabled but no notification "
                        "server could be found, disabling notifications."
                    )
                    self.notifications = False

            GLib.timeout_add(100, self.message_callback)
            if not self.loop:
                return

            self.loop.run() 
Example #11
Source File: __init__.py    From ubuntu-cleaner with GNU General Public License v3.0 6 votes vote down vote up
def _check_permission(self, sender, action):
        '''
        Verifies if the specified action is permitted, and raises
        an AccessDeniedException if not.

        The caller should use ObtainAuthorization() to get permission.
        '''

        try:
            if sender:
                kit = dbus.SystemBus().get_object('org.freedesktop.PolicyKit1', '/org/freedesktop/PolicyKit1/Authority')
                kit = dbus.Interface(kit, 'org.freedesktop.PolicyKit1.Authority')

                (granted, _, details) = kit.CheckAuthorization(
                                ('system-bus-name', {'name': sender}),
                                action, {}, dbus.UInt32(1), '', timeout=600)

                if not granted:
                    raise AccessDeniedException('Session not authorized by PolicyKit')

        except AccessDeniedException:
            raise

        except dbus.DBusException as ex:
            raise AccessDeniedException(ex.message) 
Example #12
Source File: generictomboy.py    From gtg with GNU General Public License v3.0 6 votes vote down vote up
def __exit__(self, exception_type, value, traceback):
            """
            Checks the state of the connection.
            If something went wrong for the connection, notifies the user.

            @param exception_type: the type of exception that occurred, or
                                   None
            @param value: the instance of the exception occurred, or None
            @param traceback: the traceback of the error
            @returns: False if some exception must be re-raised.
            """
            if isinstance(value, dbus.DBusException) or \
                    not self.tomboy_connection_is_ok:
                self.tomboy_failed()
                return True
            else:
                return False 
Example #13
Source File: kwallet.py    From keyring with MIT License 6 votes vote down vote up
def connected(self, service):
        if self.handle >= 0:
            if self.iface.isOpen(self.handle):
                return True

        bus = dbus.SessionBus(mainloop=DBusGMainLoop())
        wId = 0
        try:
            remote_obj = bus.get_object(self.bus_name, self.object_path)
            self.iface = dbus.Interface(remote_obj, 'org.kde.KWallet')
            self.handle = self.iface.open(self.iface.networkWallet(), wId, self.appid)
        except dbus.DBusException as e:
            raise InitError('Failed to open keyring: %s.' % e)

        if self.handle < 0:
            return False
        self._migrate(service)
        return True 
Example #14
Source File: DockAppsOptions.py    From launcher with GNU General Public License v2.0 5 votes vote down vote up
def getConfigIface():
	# Enable glib main loop support
	dbus.mainloop.glib.DBusGMainLoop(set_as_default=True)
	# Get the session bus
	bus = dbus.SessionBus()
	try:
		# Get the remote object
		remote_object = bus.get_object("org.duck.Launcher","/DBusWidget")
		# Get the remote interface for the remote object
		iface = dbus.Interface(remote_object, "org.duck.Launcher")
	except dbus.DBusException:
		iface=None

	return iface 
Example #15
Source File: player.py    From python-omxplayer-wrapper with GNU Lesser General Public License v3.0 5 votes vote down vote up
def play_sync(self):
        """
        Play the video and block whilst the video is playing
        """
        self.play()
        logger.info("Playing synchronously")
        try:
            time.sleep(0.05)
            logger.debug("Wait for playing to start")
            while self.is_playing():
                time.sleep(0.05)
        except DBusException:
            logger.error(
                "Cannot play synchronously any longer as DBus calls timed out."
            ) 
Example #16
Source File: __init__.py    From launcher with GNU General Public License v3.0 5 votes vote down vote up
def setup_dbus(force=True):
    global bus,daemon,wireless,wired
    global manager,objects,adapter,devices
    
    try:
        dbusmanager.connect_to_dbus()
    except dbus.DBusException:
        print >> sys.stderr,\
            _("Can't connect to wicd daemon,trying to start it automatically...")
    else:
        bus = dbusmanager.get_bus()
        dbus_ifaces = dbusmanager.get_dbus_ifaces()
        daemon      = dbus_ifaces["daemon"] ## @dbus.service.method('org.wicd.daemon')
        wireless    = dbus_ifaces["wireless"] ## @dbus.service.method('org.wicd.daemon.wireless')
        wired       = dbus_ifaces["wired"]    ## @
        
    
        ### BlueZ
        try:
            proxy_obj = bus.get_object("org.bluez", "/")
            manager = dbus.Interface(proxy_obj,"org.freedesktop.DBus.ObjectManager")
            objects = manager.GetManagedObjects()
            
            for path, interfaces in objects.iteritems():
                if "org.bluez.Device1" in interfaces:
                    devices[path] = interfaces["org.bluez.Device1"] ## like /org/bluez/hci0/dev_xx_xx_xx_yy_yy_yy
        
            proxy_obj = bus.get_object("org.bluez", "/org/bluez/hci0")
            adapter = dbus.Interface(proxy_obj, "org.bluez.Adapter1")
        except Exception as e:
            print(str(e))
        
        if not daemon:
            print("Error connecting to wicd via D-Bus")

        
        
        
    return True 
Example #17
Source File: qtapp.py    From autokey with GNU General Public License v3.0 5 votes vote down vote up
def _verify_not_running(self):
        if os.path.exists(common.LOCK_FILE):
            with open(common.LOCK_FILE, "r") as lock_file:
                pid = lock_file.read()
            try:
                # Check if the pid file contains garbage
                int(pid)
            except ValueError:
                logging.exception("AutoKey pid file contains garbage instead of a usable process id: " + pid)
                sys.exit(1)

            # Check that the found PID is running and is autokey
            with subprocess.Popen(["ps", "-p", pid, "-o", "command"], stdout=subprocess.PIPE) as p:
                output = p.communicate()[0].decode()
            if "autokey" in output:
                logging.debug("AutoKey is already running as pid " + pid)
                bus = dbus.SessionBus()

                try:
                    dbus_service = bus.get_object("org.autokey.Service", "/AppService")
                    dbus_service.show_configure(dbus_interface="org.autokey.Service")
                    sys.exit(0)
                except dbus.DBusException as e:
                    logging.exception("Error communicating with Dbus service")
                    self.show_error_dialog(
                        message="AutoKey is already running as pid {} but is not responding".format(pid),
                        details=str(e))
                    sys.exit(1)

        return True 
Example #18
Source File: serviceHelper.py    From backintime with GNU General Public License v2.0 5 votes vote down vote up
def _checkPolkitPrivilege(self, sender, conn, privilege):
        # from jockey
        """
        Verify that sender has a given PolicyKit privilege.

        sender is the sender's (private) D-BUS name, such as ":1:42"
        (sender_keyword in @dbus.service.methods). conn is
        the dbus.Connection object (connection_keyword in
        @dbus.service.methods). privilege is the PolicyKit privilege string.

        This method returns if the caller is privileged, and otherwise throws a
        PermissionDeniedByPolicy exception.
        """
        if sender is None and conn is None:
            # called locally, not through D-BUS
            return
        if not self.enforce_polkit:
            # that happens for testing purposes when running on the session
            # bus, and it does not make sense to restrict operations here
            return

        # query PolicyKit
        self._initPolkit()
        try:
            # we don't need is_challenge return here, since we call with AllowUserInteraction
            (is_auth, _, details) = self.polkit.CheckAuthorization(
                    ('system-bus-name', {'name': dbus.String(sender, variant_level=1)}),
                    privilege, {'': ''}, dbus.UInt32(1), '', timeout=3000)
        except dbus.DBusException as e:
            if e._dbus_error_name == 'org.freedesktop.DBus.Error.ServiceUnknown':
                # polkitd timed out, connect again
                self.polkit = None
                return self._checkPolkitPrivilege(sender, conn, privilege)
            else:
                raise

        if not is_auth:
            raise PermissionDeniedByPolicy(privilege) 
Example #19
Source File: agent.py    From bluetool with GNU General Public License v3.0 5 votes vote down vote up
def _register(self):
        try:
            manager = dbus.Interface(
                self._bus.get_object("org.bluez", "/org/bluez"),
                "org.bluez.AgentManager1")
            manager.RegisterAgent(self.path, self.capability)
            manager.RequestDefaultAgent(self.path)
        except dbus.exceptions.DBusException as error:
            logger.error(str(error) + "\n")
            return False

        return True 
Example #20
Source File: agent.py    From bluetool with GNU General Public License v3.0 5 votes vote down vote up
def _unregister(self):
        try:
            manager = dbus.Interface(
                self._bus.get_object("org.bluez", "/org/bluez"),
                "org.bluez.AgentManager1")
            manager.UnregisterAgent(self.path)
        except dbus.exceptions.DBusException:
            pass 
Example #21
Source File: test_dbus_connection.py    From python-omxplayer-wrapper with GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_raises_error_if_cant_obtain_proxy(self, BusConnection):
        self.bus.get_object = Mock(side_effect=DBusException)
        BusConnection.return_value = self.bus
        with self.assertRaises(DBusConnectionError):
            connection = self.create_example_dbus_connection() 
Example #22
Source File: test.py    From python-omxplayer-wrapper with GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_stop(self):
        self.player.stop()
        self.assertRaises(dbus.DBusException, self.player.playback_status) 
Example #23
Source File: dbus_connection.py    From python-omxplayer-wrapper with GNU Lesser General Public License v3.0 5 votes vote down vote up
def _create_proxy(self):
        try:
            # introspection fails so it is disabled
            proxy = self._bus.get_object(self._dbus_name,
                                         '/org/mpris/MediaPlayer2',
                                         introspect=False)
            return proxy
        except dbus.DBusException:
            raise DBusConnectionError('Could not get proxy object')



# The python dbus bindings don't provide property access via the
# 'org.freedesktop.DBus.Properties' interface so we wrap the access of
# properties using 
Example #24
Source File: tomboy.py    From gtg with GNU General Public License v3.0 5 votes vote down vote up
def getTomboyObject(self):
        bus = dbus.SessionBus()
        try:
            obj = bus.get_object("org.gnome.Tomboy",
                                 "/org/gnome/Tomboy/RemoteControl")
        except dbus.DBusException:
            DIALOG_DESTROY_WITH_PARENT = Gtk.DialogFlags.DESTROY_WITH_PARENT
            if not hasattr(self, "disable_flag"):
                message = _(
                    "%s seems to be installed on your system, but it does "
                    "not provide a DBus interface which is required by the "
                    "Tomboy/Gnote plugin in GTG.") % self.software.title()
                dialog = Gtk.MessageDialog(
                    parent=self.plugin_api.get_ui().get_window(),
                    flags=DIALOG_DESTROY_WITH_PARENT,
                    type=Gtk.MessageType.ERROR,
                    buttons=Gtk.ButtonsType.OK,
                    message_format=message,
                )
                dialog.run()
                dialog.destroy()
                self.disable_flag = True
            return None
        return dbus.Interface(obj, "org.gnome.Tomboy.RemoteControl")

    # gets the list of the titles of the notes 
Example #25
Source File: generictomboy.py    From gtg with GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, backend, bus_name, bus_path, bus_interface):
            """
            Sees if a TomboyConnection object already exists. If so, since we
            are inheriting from a Borg object, the initialization already took
            place.
            If not, it tries to connect to Tomboy via Dbus. If the connection
            is not possible, the user is notified about it.

            @param backend: a reference to a Backend
            @param bus_name: the DBus address of Tomboy
            @param bus_path: the DBus path of Tomboy RemoteControl
            @param bus_interface: the DBus address of Tomboy RemoteControl
            """
            super().__init__()
            if hasattr(self, "tomboy_connection_is_ok") and \
                    self.tomboy_connection_is_ok:
                return
            self.backend = backend
            self.tomboy_connection_is_ok = True
            with GenericTomboy.DbusWatchdog(backend):
                bus = dbus.SessionBus()
                try:
                    obj = bus.get_object(bus_name, bus_path)
                    self.tomboy = dbus.Interface(obj, bus_interface)
                except dbus.DBusException:
                    self.tomboy_failed()
                    self.tomboy = None 
Example #26
Source File: interface.py    From kano-settings with GNU General Public License v2.0 5 votes vote down vote up
def stop_discovering_devices():
    if not is_bluetooth_available():
        logger.warn("No bluetooth available")
        return

    try:
        get_adaptor_iface().StopDiscovery()
    except dbus.DBusException as e:
        logger.error("Error exiting bluetooth discovery mode. " \
                     "This is likely because DBus isn't ready",
                     exception=e) 
Example #27
Source File: interface.py    From kano-settings with GNU General Public License v2.0 5 votes vote down vote up
def discover_devices():
    if not is_bluetooth_available():
        logger.warn("No bluetooth available")
        return

    try:
        get_adaptor_iface().StartDiscovery()
    except dbus.DBusException as e:
        logger.error("Error entering bluetooth discovery mode. " \
                     "This is likely because DBus isn't ready",
                     exception=e) 
Example #28
Source File: device.py    From kano-settings with GNU General Public License v2.0 5 votes vote down vote up
def unfuse(self):
        try:
            self.trusted = False
            self.disconnect()
            return True
        except dbus.DBusException:
            logger.error(
                "Unfusing failed: the dbus service probably did not reply"
            )
            return False 
Example #29
Source File: device.py    From kano-settings with GNU General Public License v2.0 5 votes vote down vote up
def fuse(self):
        '''
        Perform actions to bind this device to the adapter
        '''
        try:
            self.pair()
            self.connect()
            self.trusted = self.paired
            return self.trusted
        except dbus.DBusException:
            logger.error(
                "Fusing failed: the dbus service probably did not reply"
            )
            return False 
Example #30
Source File: device.py    From kano-settings with GNU General Public License v2.0 5 votes vote down vote up
def connect(self):
        if self.connected:
            return

        try:
            self.interface.Connect()
        except dbus.DBusException:
            # Probably means the device has come out of discover mode
            return False
        return self.connected