Python dbus.SessionBus() Examples

The following are 30 code examples of dbus.SessionBus(). 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: __init__.py    From spotify-lyrics-cli with GNU General Public License v3.0 8 votes vote down vote up
def get_song_info(player):
    if player == "mpd":
        from mpd import MPDClient
        client = MPDClient()
        client.connect("localhost", 6600)
        song_info = client.currentsong()
        return song_info["artist"], song_info["title"]
    else:
        bus = dbus.SessionBus()
        try:
            proxy = bus.get_object("org.mpris.MediaPlayer2.%s" % player,
                                   "/org/mpris/MediaPlayer2")
        except dbus.exceptions.DBusException:
            print("[ERROR] Player \"%s\" doesn't exist or isn't playing" \
                  % player)
            return

        interface = dbus.Interface(
            proxy, dbus_interface="org.freedesktop.DBus.Properties"
        )
        properties = interface.GetAll("org.mpris.MediaPlayer2.Player")
        metadata = properties["Metadata"]
        artist = str(metadata["xesam:artist"][0])
        title = str(metadata["xesam:title"])
        return artist, title 
Example #2
Source File: graphroute.py    From ivre with GNU General Public License v3.0 7 votes vote down vote up
def display3dgraph(graph, reset_world=True):
        """Send the graph (produced by buildgraph()) to a running
        rtgraph3d instance.

        """
        dbus.mainloop.glib.DBusGMainLoop(set_as_default=True)
        bus = dbus.SessionBus()
        control = bus.get_object("org.secdev.rtgraph3d", "/control")
        graph3d = dbus.Interface(control, "org.secdev.rtgraph3d.command")
        if reset_world:
            graph3d.reset_world()
        for node, node_edges in viewitems(graph):
            for destnode in node_edges:
                if destnode == node:
                    continue
                try:
                    graph3d.new_edge(utils.int2ip(node), {},
                                     utils.int2ip(destnode), {})
                except Exception:
                    utils.LOGGER.warning('Exception', exc_info=True)
        return graph3d 
Example #3
Source File: util.py    From python-eduvpn-client with GNU General Public License v3.0 6 votes vote down vote up
def have_dbus_notification_service():
    # type: () -> bool
    try:
        import dbus
        dbus = dbus.SessionBus(private=True)
        proxy = dbus.get_object('org.freedesktop.Notifications', '/org/freedesktop/Notifications')
    except NameExistsException as e:
        logger.error(u"WARNING: dbus notification service not available, eduVPN client functionality limited")
        dbus.close()
        return False
    except Exception as e:
        logger.error(u"WARNING: dbus daemon not running, eduVPN client functionality limited")
        return False
    else:
        dbus.close()
        return True 
Example #4
Source File: sound_menu.py    From lplayer with MIT License 6 votes vote down vote up
def __init__(self, desktop_name):
        """
        Creates a SoundMenuControls object.

        Requires a dbus loop to be created before the gtk mainloop,
        typically by calling DBusGMainLoop(set_as_default=True).

        arguments:
        desktop_name: The name of the desktop file for the application,
        such as, "simple-player" to refer to the file: simple-player.desktop.

        """

        self.desktop_name = desktop_name
        bus_str = """org.mpris.MediaPlayer2.%s""" % desktop_name
        bus_name = dbus.service.BusName(bus_str, bus=dbus.SessionBus())
        dbus.service.Object.__init__(self, bus_name, "/org/mpris/MediaPlayer2")
        self.__playback_status = "Stopped"

        self.song_changed() 
Example #5
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 #6
Source File: interface.py    From Pytify with MIT License 6 votes vote down vote up
def factory(type):
        try:
            interface = dbus.Interface(
                dbus.SessionBus().get_object(
                    'org.mpris.MediaPlayer2.spotify',
                    '/org/mpris/MediaPlayer2'
                ),
                type
            )
        except dbus.exceptions.DBusException:
            """
                If we catch this exception, Spotify is not running.
                Let the user know.
            """
            sys.exit(
                "\nSome errors occured. Try restart or start Spotify. Pytify is just a cli application which controls Spotify. So you can't use Pytify without Spotify.\n"
            )

        return interface 
Example #7
Source File: __init__.py    From FeelUOwn with GNU General Public License v3.0 6 votes vote down vote up
def run_mpris2_server(app):
    try:
        import dbus
        import dbus.service
        import dbus.mainloop.pyqt5
    except ImportError as e:
        logger.error("can't run mpris2 server: %s",  str(e))
    else:
        from .mpris2 import Mpris2Service, BusName

        # check if a mainloop was already set
        mainloop = dbus.get_default_main_loop()
        if mainloop is not None:
            logger.warn("mpris2 service already enabled? "
                        "maybe you should remove feeluown-mpris2-plugin")
            return

        # set the mainloop before any dbus operation
        dbus.mainloop.pyqt5.DBusQtMainLoop(set_as_default=True)
        session_bus = dbus.SessionBus()
        bus = dbus.service.BusName(BusName, session_bus)
        service = Mpris2Service(app, bus)
        service.enable() 
Example #8
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 #9
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 #10
Source File: gnomecast.py    From gnomecast with GNU General Public License v3.0 6 votes vote down vote up
def __init__(self):
    self.ip = (([ip for ip in socket.gethostbyname_ex(socket.gethostname())[2] if not ip.startswith("127.")] or [[(s.connect(("8.8.8.8", 53)), s.getsockname()[0], s.close()) for s in [socket.socket(socket.AF_INET, socket.SOCK_DGRAM)]][0][1]]) + [None])[0]
    with contextlib.closing(socket.socket(socket.AF_INET, socket.SOCK_STREAM)) as s:
      s.bind(('0.0.0.0', 0))
      self.port = s.getsockname()[1]
    self.app = bottle.Bottle()
    self.cast = None
    self.last_known_player_state = None
    self.last_known_current_time = None
    self.last_time_current_time = None
    self.fn = None
    self.video_stream = None
    self.audio_stream = None
    self.last_fn_played = None
    self.transcoder = None
    self.duration = None
    self.subtitles = None
    self.seeking = False
    self.last_known_volume_level = None
    bus = dbus.SessionBus() if DBUS_AVAILABLE else None
    self.saver_interface = find_screensaver_dbus_iface(bus)
    self.inhibit_screensaver_cookie = None
    self.autoplay = False 
Example #11
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 #12
Source File: fx.py    From openrazer with GNU General Public License v2.0 6 votes vote down vote up
def __init__(self, serial: str, capabilities: dict, daemon_dbus=None, matrix_dims=(-1, -1)):
        super(RazerAdvancedFX, self).__init__(serial, capabilities, daemon_dbus)

        # Only init'd when there's a matrix
        self._capabilities = capabilities

        if not all([dim >= 1 for dim in matrix_dims]):
            raise ValueError("Matrix dimensions cannot contain -1")

        if daemon_dbus is None:
            session_bus = _dbus.SessionBus()
            daemon_dbus = session_bus.get_object("org.razer", "/org/razer/device/{0}".format(serial))

        self._matrix_dims = matrix_dims
        self._lighting_dbus = _dbus.Interface(daemon_dbus, "razer.device.lighting.chroma")

        self.matrix = Frame(matrix_dims) 
Example #13
Source File: Shutdown.py    From bcloud with GNU General Public License v3.0 6 votes vote down vote up
def _prepair(self):
        '''Try to connect to the given dbus services. If successful it will
        return a callable dbus proxy and those arguments.
        '''
        try:
            sessionbus = dbus.SessionBus()
            systembus  = dbus.SystemBus()
        except:
            return (None, None)
        for dbus_props in self.DBUS_SHUTDOWN.values():
            try:
                if dbus_props['bus'] == SESSION_BUS:
                    bus = sessionbus
                else:
                    bus = systembus
                interface = bus.get_object(dbus_props['service'],
                                           dbus_props['objectPath'])
                proxy = interface.get_dbus_method(dbus_props['method'],
                                                  dbus_props['interface'])
                return (proxy, dbus_props['arguments'])
            except dbus.exceptions.DBusException:
                continue
        return (None, None) 
Example #14
Source File: kde.py    From QuickWall with MIT License 6 votes vote down vote up
def setwallpaper(filepath):
    """
    This script is taken from https://github.com/pashazz/ksetwallpaper/

    All the credit goes to the user for the code, I'm just using it
    to add a functionality to my app.
    """

    jscript = """var allDesktops = desktops();
    for ( i = 0; i < allDesktops.length;i++ ) {
        d = allDesktops[i];
        d.wallpaperPlugin = "org.kde.image";
        d.currentConfigGroup = Array("Wallpaper", "org.kde.image", "General");
        d.writeConfig("Image", "file://%s")
    }
    """
    bus = dbus.SessionBus()
    plasma = dbus.Interface(bus.get_object('org.kde.plasmashell', '/PlasmaShell'), dbus_interface='org.kde.PlasmaShell')
    plasma.evaluateScript(jscript % filepath) 
Example #15
Source File: kde.py    From QuickWall with MIT License 6 votes vote down vote up
def restoreWallpaper():
    """
    Load wallpaper from RestorableImage config
    """
    
    jscript = """var first = desktopForScreen(0);
    first.currentConfigGroup = Array( 'Wallpaper', 'org.kde.image', 'General' );
    var img = first.readConfig('RestorableImage');
    var allDesktops = desktops();
    for ( i = 0; i < allDesktops.length;i++ ) {
        d = allDesktops[i];
        d.wallpaperPlugin = "org.kde.image";
        d.currentConfigGroup = Array("Wallpaper", "org.kde.image", "General");
        d.writeConfig("Image", img)
    }
    """
    bus = dbus.SessionBus()
    plasma = dbus.Interface(bus.get_object('org.kde.plasmashell', '/PlasmaShell'), dbus_interface='org.kde.PlasmaShell')
    plasma.evaluateScript(jscript) 
Example #16
Source File: scanner_client.py    From openscap-daemon with GNU Lesser General Public License v2.1 6 votes vote down vote up
def __init__(self, number=2,
                 logfile=os.path.join(image_tmp, "openscap.log"),
                 onlycache=False,
                 reportdir=image_tmp, workdir=image_tmp):

        self.arg_tup = self.tup(number=number, logfile=logfile,
                                onlycache=onlycache, reportdir=reportdir,
                                workdir=workdir)

        self.arg_dict = {'number': number, 'logfile': logfile,
                         'onlycache': onlycache, 'reportdir': reportdir,
                         'workdir': workdir}
        self._docker_ping()
        self.num_threads = number
        self.bus = dbus.SessionBus()
        self.dbus_object = self.bus.get_object(dbus_utils.BUS_NAME,
                                               dbus_utils.OBJECT_PATH)
        self.logfile = logfile
        self.onlycache = onlycache
        self.reportdir = reportdir
        self.workdir = workdir
        self.onlyactive = False
        self.allcontainers = False
        self.allimages = False
        self.images = False 
Example #17
Source File: gnome-pass-search-provider.py    From gnome-pass-search-provider with GNU General Public License v3.0 5 votes vote down vote up
def __init__(self):
        self.session_bus = dbus.SessionBus()
        bus_name = dbus.service.BusName(self.bus_name, bus=self.session_bus)
        dbus.service.Object.__init__(self, bus_name, self._object_path)
        self.password_store = getenv("PASSWORD_STORE_DIR") or expanduser(
            "~/.password-store"
        ) 
Example #18
Source File: tools.py    From backintime with GNU General Public License v2.0 5 votes vote down vote up
def _prepair(self):
        """
        Try to connect to the given dbus services. If successful it will
        return a callable dbus proxy and those arguments.
        """
        try:
            if 'DBUS_SESSION_BUS_ADDRESS' in os.environ:
                sessionbus = dbus.bus.BusConnection(os.environ['DBUS_SESSION_BUS_ADDRESS'])
            else:
                sessionbus = dbus.SessionBus()
            systembus  = dbus.SystemBus()
        except:
            return((None, None))
        des = list(self.DBUS_SHUTDOWN.keys())
        des.sort()
        for de in des:
            if de == 'gnome' and self.unity7():
                continue
            dbus_props = self.DBUS_SHUTDOWN[de]
            try:
                if dbus_props['bus'] == 'sessionbus':
                    bus = sessionbus
                else:
                    bus = systembus
                interface = bus.get_object(dbus_props['service'], dbus_props['objectPath'])
                proxy = interface.get_dbus_method(dbus_props['method'], dbus_props['interface'])
                return((proxy, dbus_props['arguments']))
            except dbus.exceptions.DBusException:
                continue
        return((None, None)) 
Example #19
Source File: ipaddress.py    From my-weather-indicator with MIT License 5 votes vote down vote up
def get_current_location_option1():
    '''Gets the current location from geolocation via IP (only method
       currently supported)
    '''
    latitude = 0
    longitude = 0
    bus = dbus.SessionBus()

    # For now we default to the UbuntuGeoIP provider and we fall back to
    # Hostip. We should probably be cleverer about provider detection, but
    # this solution works for now and does not rely solely on UbuntuGeoIP,
    # which means qreator can run on other distros
    try:
        geoclue = bus.get_object(
            'org.freedesktop.Geoclue.Providers.UbuntuGeoIP',
            '/org/freedesktop/Geoclue/Providers/UbuntuGeoIP')
        position_info = geoclue.GetPosition(
            dbus_interface='org.freedesktop.Geoclue.Position')
        latitude = convert(position_info[2])
        longitude = convert(position_info[3])
    except dbus.exceptions.DBusException as e:
        print('Error 1', e)
        try:
            geoclue = bus.get_object(
                'org.freedesktop.Geoclue.Providers.Hostip',
                '/org/freedesktop/Geoclue/Providers/Hostip')
            position_info = geoclue.GetPosition(
                dbus_interface='org.freedesktop.Geoclue.Position')
            latitude = convert(position_info[2])
            longitude = convert(position_info[3])
        except dbus.exceptions.DBusException as e:
            print('Error 2', e)
    return latitude, longitude 
Example #20
Source File: bard.py    From bard with GNU General Public License v3.0 5 votes vote down vote up
def getCurrentlyPlayingSongs(self):
        bus = dbus.SessionBus()
        names = [x for x in bus.list_names()
                 if x.startswith('org.mpris.MediaPlayer2.mpv')]
        if len(names) == 0:
            return []
        songs = []
        pausedSongs = []
        path = None
        playingSongPath = None
        for name in names:
            mpv = bus.get_object(name, '/org/mpris/MediaPlayer2')
            properties = dbus.Interface(mpv, 'org.freedesktop.DBus.Properties')
            playbackStatus = properties.Get('org.mpris.MediaPlayer2.Player',
                                            'PlaybackStatus')
            if playbackStatus != 'Playing' and playbackStatus != 'Paused':
                continue
            metadata = properties.Get('org.mpris.MediaPlayer2.Player',
                                      'Metadata')
            url = urllib.parse.urlparse(metadata['xesam:url'])
            path = urllib.parse.unquote(url.path)
            newSongs = getSongsAtPath(path, exact=True)
            if playbackStatus == 'Playing':
                playingSongPath = path
                songs.extend([x for x in newSongs
                              if x.id not in [y.id for y in songs]])
            else:
                pausedSongs.extend([x for x in newSongs if x.id not in
                                    [y.id for y in pausedSongs]])

        if songs:
            return songs
        if len(pausedSongs) == 1:
            return pausedSongs

        if playingSongPath:
            print("Couldn't find song in database:", playingSongPath)
        return [] 
Example #21
Source File: notifications.py    From rssit with MIT License 5 votes vote down vote up
def __init__(self):
        bus = dbus.SessionBus()
        bus.request_name("org.freedesktop.Notifications")
        bus_name = dbus.service.BusName("org.freedesktop.Notifications", bus=bus)
        dbus.service.Object.__init__(self, bus_name, '/org/freedesktop/Notifications') 
Example #22
Source File: osd.py    From clay with GNU General Public License v3.0 5 votes vote down vote up
def __init__(self):
        self._last_id = 0

        if IS_INIT:
            self.bus = SessionBus()
            self.notifcations = self.bus.get_object(
                "org.freedesktop.Notifications",
                "/org/freedesktop/Notifications"
            )
            self.notify_interface = Interface(self.notifcations, "org.freedesktop.Notifications") 
Example #23
Source File: i3-appmenu-service.py    From i3-hud-menu with MIT License 5 votes vote down vote up
def __init__(self):
    bus_name = dbus.service.BusName('com.canonical.AppMenu.Registrar', bus = dbus.SessionBus())
    dbus.service.Object.__init__(self, bus_name, '/com/canonical/AppMenu/Registrar')
    self.window_dict = dict() 
Example #24
Source File: mpris2_np.py    From code with MIT License 5 votes vote down vote up
def list_players(prefix=BUS_NAME_PREFIX_V2):
    bus = dbus.SessionBus()
    return [name[len(prefix):] for name in bus.list_names()
                               if name.startswith(prefix)] 
Example #25
Source File: mpris2_np.py    From code with MIT License 5 votes vote down vote up
def get_player(name):
    bus = dbus.SessionBus()
    try:
        return bus.get_object(BUS_NAME_PREFIX_V2 + name, '/org/mpris/MediaPlayer2')
    except TypeError:
        raise FubarException() 
Example #26
Source File: do_timeout.py    From pomodoroTasks2 with GNU General Public License v3.0 5 votes vote down vote up
def __init__(self):
        self.tw = TaskWarrior()
        builder.add_from_file("gui/timeout.glade")
        self.wTimeout     = builder.get_object("wTimeout")
        self.pbTimeout    = builder.get_object("pbTimeout")
        self.wContinue    = builder.get_object("wContinue")
        self.lsbReminders = builder.get_object("lsbReminders")
        self.bus = dbus.SessionBus()
        self.session_bus = self.bus.get_object('org.liloman.pomodoro', "/daemon")
        self.interface = dbus.Interface(self.session_bus, "org.liloman.pomodoroInterface")

        ################
        #  Set events  #
        ################

        self.btYes = builder.get_object("btYes")
        self.btYes.connect("clicked",self.onYesPressed)
        self.btNo = builder.get_object("btNo")
        self.btNo.connect("clicked",self.onNoPressed)
        self.wTimeout.connect("delete-event",self.onDeleteWindow)
        self.btBack = builder.get_object("btBackWork")
        self.btBack.connect("clicked",self.onBackWorkPressed)
        self.pbTimeout = builder.get_object("pbTimeout")

        DATEFORMAT='%d/%m/%Y %H:%M'
        for task in self.tw.tasks.filter('+READY +reminder'):
                #get all fields in task
                task.refresh()
                self.addReminder(task['description'],task['due'].strftime(DATEFORMAT))

    ###############
    #  Reminders  #
    ############### 
Example #27
Source File: fx.py    From openrazer with GNU General Public License v2.0 5 votes vote down vote up
def __init__(self, serial: str, capabilities: dict, daemon_dbus=None):
        self._capabilities = capabilities

        if daemon_dbus is None:
            session_bus = _dbus.SessionBus()
            daemon_dbus = session_bus.get_object("org.razer", "/org/razer/device/{0}".format(serial))
        self._dbus = daemon_dbus 
Example #28
Source File: macro.py    From openrazer with GNU General Public License v2.0 5 votes vote down vote up
def __init__(self, serial: str, devname: str, daemon_dbus=None, capabilities=None):
        if daemon_dbus is None:
            session_bus = _dbus.SessionBus()
            daemon_dbus = session_bus.get_object("org.razer", "/org/razer/device/{0}".format(serial))

        if capabilities is None:
            self._capabilities = {}
        else:
            self._capabilities = capabilities

        self._macro_dbus = _dbus.Interface(daemon_dbus, "razer.device.macro")

        self._macro_enabled = False

        self.name = devname 
Example #29
Source File: screensaver_monitor.py    From openrazer with GNU General Public License v2.0 5 votes vote down vote up
def __init__(self, parent):
        self._logger = logging.getLogger('razer.screensaver')
        self._logger.info("Initialising DBus Screensaver Monitor")

        self._parent = parent
        self._monitoring = True
        self._active = None

        self._dbus_instances = []
        # Get session bus
        bus = dbus.SessionBus()
        # Loop through and monitor the signals
        for screensaver_interface in DBUS_SCREENSAVER_INTERFACES:
            bus.add_signal_receiver(self.signal_callback, dbus_interface=screensaver_interface, signal_name='ActiveChanged') 
Example #30
Source File: tools.py    From backintime with GNU General Public License v2.0 5 votes vote down vote up
def inhibitSuspend(app_id = sys.argv[0],
                    toplevel_xid = None,
                    reason = 'take snapshot',
                    flags = INHIBIT_SUSPENDING | INHIBIT_IDLE):
    """
    Prevent machine to go to suspend or hibernate.
    Returns the inhibit cookie which is used to end the inhibitor.
    """
    if ON_TRAVIS or dbus is None:
        # no suspend on travis (no dbus either)
        return
    if not app_id:
        app_id = 'backintime'
    try:
        if not toplevel_xid:
            toplevel_xid = 0
    except IndexError:
        toplevel_xid = 0

    for dbus_props in INHIBIT_DBUS:
        try:
            #connect directly to the socket instead of dbus.SessionBus because
            #the dbus.SessionBus was initiated before we loaded the environ
            #variables and might not work
            if 'DBUS_SESSION_BUS_ADDRESS' in os.environ:
                bus = dbus.bus.BusConnection(os.environ['DBUS_SESSION_BUS_ADDRESS'])
            else:
                bus = dbus.SessionBus()
            interface = bus.get_object(dbus_props['service'], dbus_props['objectPath'])
            proxy = interface.get_dbus_method(dbus_props['methodSet'], dbus_props['interface'])
            cookie = proxy(*[(app_id, dbus.UInt32(toplevel_xid), reason, dbus.UInt32(flags))[i] for i in dbus_props['arguments']])
            logger.debug('Inhibit Suspend started. Reason: {}'.format(reason))
            return (cookie, bus, dbus_props)
        except dbus.exceptions.DBusException:
            pass
    if isRoot():
        logger.debug("Inhibit Suspend failed because BIT was started as root.")
        return
    logger.warning('Inhibit Suspend failed.')