Python dbus.Interface() Examples

The following are 30 code examples of dbus.Interface(). 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: gatt_linux.py    From gatt-python with MIT License 7 votes vote down vote up
def __init__(self, adapter_name):
        self.listener = None
        self.adapter_name = adapter_name

        self._bus = dbus.SystemBus()
        try:
            adapter_object = self._bus.get_object('org.bluez', '/org/bluez/' + adapter_name)
        except dbus.exceptions.DBusException as e:
            raise _error_from_dbus_error(e)
        object_manager_object = self._bus.get_object("org.bluez", "/")
        self._adapter = dbus.Interface(adapter_object, 'org.bluez.Adapter1')
        self._adapter_properties = dbus.Interface(self._adapter, 'org.freedesktop.DBus.Properties')
        self._object_manager = dbus.Interface(object_manager_object, "org.freedesktop.DBus.ObjectManager")
        self._device_path_regex = re.compile('^/org/bluez/' + adapter_name + '/dev((_[A-Z0-9]{2}){6})$')
        self._devices = {}
        self._discovered_devices = {}
        self._interface_added_signal = None
        self._properties_changed_signal = None
        self._main_loop = None

        self.update_devices() 
Example #3
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 #4
Source File: test_restful.py    From keylime with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def test_020_agent_keys_pubkey_get(self):
        """Test agent's GET /v2/keys/pubkey Interface"""

        # We want a real cloud agent to communicate with!
        launch_cloudagent()
        time.sleep(10)
        params = f"/v{self.api_version}/keys/pubkey"
        response = httpclient_requests.request("GET", "%s"%tenant_templ.cloudagent_ip,tenant_templ.cloudagent_port, params=params)

        self.assertEqual(response.status, 200, "Non-successful Agent pubkey return code!")
        json_response = json.loads(response.read().decode())

        # Ensure response is well-formed
        self.assertIn("results", json_response, "Malformed response body!")
        self.assertIn("pubkey", json_response["results"], "Malformed response body!")

        global public_key
        public_key = json_response["results"]["pubkey"]
        self.assertNotEqual(public_key, None, "Malformed response body!") 
Example #5
Source File: openshift_facts.py    From origin-ci-tool with Apache License 2.0 6 votes vote down vote up
def is_service_running(service):
    """ Queries systemd through dbus to see if the service is running """
    service_running = False
    bus = SystemBus()
    systemd = bus.get_object('org.freedesktop.systemd1', '/org/freedesktop/systemd1')
    manager = Interface(systemd, dbus_interface='org.freedesktop.systemd1.Manager')
    try:
        service_unit = service if service.endswith('.service') else manager.GetUnit('{0}.service'.format(service))
        service_proxy = bus.get_object('org.freedesktop.systemd1', str(service_unit))
        service_properties = Interface(service_proxy, dbus_interface='org.freedesktop.DBus.Properties')
        service_load_state = service_properties.Get('org.freedesktop.systemd1.Unit', 'LoadState')
        service_active_state = service_properties.Get('org.freedesktop.systemd1.Unit', 'ActiveState')
        if service_load_state == 'loaded' and service_active_state == 'active':
            service_running = True
    except DBusException:
        pass

    return service_running 
Example #6
Source File: openshift_facts.py    From origin-ci-tool with Apache License 2.0 6 votes vote down vote up
def is_service_running(service):
    """ Queries systemd through dbus to see if the service is running """
    service_running = False
    bus = SystemBus()
    systemd = bus.get_object('org.freedesktop.systemd1', '/org/freedesktop/systemd1')
    manager = Interface(systemd, dbus_interface='org.freedesktop.systemd1.Manager')
    try:
        service_unit = service if service.endswith('.service') else manager.GetUnit('{0}.service'.format(service))
        service_proxy = bus.get_object('org.freedesktop.systemd1', str(service_unit))
        service_properties = Interface(service_proxy, dbus_interface='org.freedesktop.DBus.Properties')
        service_load_state = service_properties.Get('org.freedesktop.systemd1.Unit', 'LoadState')
        service_active_state = service_properties.Get('org.freedesktop.systemd1.Unit', 'ActiveState')
        if service_load_state == 'loaded' and service_active_state == 'active':
            service_running = True
    except DBusException:
        pass

    return service_running 
Example #7
Source File: test_restful.py    From keylime with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def test_041_agent_keys_verify_get(self):
        """Test agent's GET /v2/keys/verify Interface
        We use async here to allow function await while key processes"""
        self.assertIsNotNone(self.K, "Required value not set.  Previous step may have failed?")
        challenge = tpm_abstract.TPM_Utilities.random_password(20)
        encoded = base64.b64encode(self.K).decode('utf-8')

        response = tornado_requests.request("GET",
                                    "http://%s:%s/keys/verify?challenge=%s"%(self.cloudagent_ip,self.cloudagent_port,challenge))
        response = await response
        self.assertEqual(response.status, 200, "Non-successful Agent verify return code!")
        json_response = json.loads(response.read().decode())

        # Ensure response is well-formed
        self.assertIn("results", json_response, "Malformed response body!")
        self.assertIn("hmac", json_response["results"], "Malformed response body!")

        # Be sure response is valid
        mac = json_response['results']['hmac']
        ex_mac = crypto.do_hmac(encoded, challenge)
        # ex_mac = crypto.do_hmac(self.K, challenge)
        self.assertEqual(mac, ex_mac, "Agent failed to validate challenge code!") 
Example #8
Source File: test_restful.py    From keylime with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def test_011_reg_agent_activate_put(self):
        """Test registrar's PUT /v2/agents/{UUID}/activate Interface"""
        global keyblob, aik

        self.assertIsNotNone(keyblob, "Required value not set.  Previous step may have failed?")
        self.assertIsNotNone(aik, "Required value not set.  Previous step may have failed?")

        key = tpm.activate_identity(keyblob)

        data = {
            'auth_tag': crypto.do_hmac(key,tenant_templ.agent_uuid),
        }
        v_json_message = json.dumps(data)

        params = f"/v{self.api_version}/agents/{tenant_templ.agent_uuid}/activate"
        response = httpclient_requests.request("PUT", "%s"%tenant_templ.registrar_ip,tenant_templ.registrar_boot_port, params=params, data=v_json_message, context=None)
        self.assertEqual(response.status, 200, "Non-successful Registrar agent Activate return code!")
        json_response = json.loads(response.read().decode())

        # Ensure response is well-formed
        self.assertIn("results", json_response, "Malformed response body!") 
Example #9
Source File: test_restful.py    From keylime with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def test_012_reg_agent_vactivate_put(self):
        """Test registrar's PUT /v2/agents/{UUID}/vactivate Interface"""
        global keyblob, aik, ek

        self.assertIsNotNone(keyblob, "Required value not set.  Previous step may have failed?")
        self.assertIsNotNone(aik, "Required value not set.  Previous step may have failed?")
        self.assertIsNotNone(ek, "Required value not set.  Previous step may have failed?")

        key = tpm.activate_identity(keyblob)
        deepquote = tpm.create_deep_quote(hashlib.sha1(key).hexdigest(),tenant_templ.agent_uuid+aik+ek)
        data = {
            'deepquote': deepquote,
        }
        v_json_message = json.dumps(data)

        params = '/v%s/agents/%s/vactivate'% self.api_version, tenant_templ.agent_uuid
        response = httpclient_requests.request("PUT", "%s"%tenant_templ.registrar_ip,tenant_templ.registrar_tls_boot_port, params=params, data=v_json_message, context=tenant_templ.context)
        self.assertEqual(response.status, 200, "Non-successful Registrar agent vActivate return code!")
        json_response = json.loads(response.read().decode())

        # Ensure response is well-formed
        self.assertIn("results", json_response, "Malformed response body!") 
Example #10
Source File: bluezutils.py    From DirtyTooth-RaspberryPi with GNU Affero General Public License v3.0 6 votes vote down vote up
def find_device_in_objects(objects, device_address, adapter_pattern=None):
	bus = dbus.SystemBus()
	path_prefix = ""
	if adapter_pattern:
		adapter = find_adapter_in_objects(objects, adapter_pattern)
		path_prefix = adapter.object_path
	for path, ifaces in objects.iteritems():
		device = ifaces.get(DEVICE_INTERFACE)
		if device is None:
			continue
		if (device["Address"] == device_address and
						path.startswith(path_prefix)):
			obj = bus.get_object(SERVICE_NAME, path)
			return dbus.Interface(obj, DEVICE_INTERFACE)

	raise Exception("Bluetooth device not found") 
Example #11
Source File: openshift_facts.py    From origin-ci-tool with Apache License 2.0 6 votes vote down vote up
def is_service_running(service):
    """ Queries systemd through dbus to see if the service is running """
    service_running = False
    bus = SystemBus()
    systemd = bus.get_object('org.freedesktop.systemd1', '/org/freedesktop/systemd1')
    manager = Interface(systemd, dbus_interface='org.freedesktop.systemd1.Manager')
    try:
        service_unit = service if service.endswith('.service') else manager.GetUnit('{0}.service'.format(service))
        service_proxy = bus.get_object('org.freedesktop.systemd1', str(service_unit))
        service_properties = Interface(service_proxy, dbus_interface='org.freedesktop.DBus.Properties')
        service_load_state = service_properties.Get('org.freedesktop.systemd1.Unit', 'LoadState')
        service_active_state = service_properties.Get('org.freedesktop.systemd1.Unit', 'ActiveState')
        if service_load_state == 'loaded' and service_active_state == 'active':
            service_running = True
    except DBusException:
        pass

    return service_running 
Example #12
Source File: openshift_facts.py    From origin-ci-tool with Apache License 2.0 6 votes vote down vote up
def is_service_running(service):
    """ Queries systemd through dbus to see if the service is running """
    service_running = False
    bus = SystemBus()
    systemd = bus.get_object('org.freedesktop.systemd1', '/org/freedesktop/systemd1')
    manager = Interface(systemd, dbus_interface='org.freedesktop.systemd1.Manager')
    try:
        service_unit = service if service.endswith('.service') else manager.GetUnit('{0}.service'.format(service))
        service_proxy = bus.get_object('org.freedesktop.systemd1', str(service_unit))
        service_properties = Interface(service_proxy, dbus_interface='org.freedesktop.DBus.Properties')
        service_load_state = service_properties.Get('org.freedesktop.systemd1.Unit', 'LoadState')
        service_active_state = service_properties.Get('org.freedesktop.systemd1.Unit', 'ActiveState')
        if service_load_state == 'loaded' and service_active_state == 'active':
            service_running = True
    except DBusException:
        pass

    return service_running 
Example #13
Source File: systemd.py    From ideascube with GNU Affero General Public License v3.0 6 votes vote down vote up
def __init__(self, path):
        proxy = dbus.SystemBus().get_object('org.freedesktop.systemd1', path)
        self._unit = dbus.Interface(
            proxy, dbus_interface='org.freedesktop.systemd1.Unit')

        props = self._unit.GetAll(
            'org.freedesktop.systemd1.Unit',
            dbus_interface=dbus.PROPERTIES_IFACE)

        for prop in props:
            prop = str(prop)

            if not hasattr(self.__class__, prop):
                setattr(self.__class__, prop, self._make_property(prop))

        if self.LoadState == 'not-found':
            raise NoSuchUnit(self.Id) 
Example #14
Source File: test_restful.py    From keylime with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def test_024_agent_keys_ukey_post(self):
        """Test agents's POST /v2/keys/ukey Interface"""
        global public_key

        self.assertIsNotNone(public_key, "Required value not set.  Previous step may have failed?")
        self.assertIsNotNone(self.U, "Required value not set.  Previous step may have failed?")
        self.assertIsNotNone(self.auth_tag, "Required value not set.  Previous step may have failed?")
        self.assertIsNotNone(self.payload, "Required value not set.  Previous step may have failed?")

        encrypted_U = crypto.rsa_encrypt(crypto.rsa_import_pubkey(public_key),self.U)
        b64_encrypted_u = base64.b64encode(encrypted_U)
        data = {
                  'encrypted_key': b64_encrypted_u,
                  'auth_tag': self.auth_tag,
                  'payload': self.payload
                }
        u_yaml_message = json.dumps(data)

        params = '/v%s/keys/ukey'% self.api_version
        response = httpclient_requests.request("POST", "%s"%tenant_templ.cloudagent_ip,tenant_templ.cloudagent_port, params=params, data=u_yaml_message)
        self.assertEqual(response.status, 200, "Non-successful Agent ukey post return code!")
        json_response = json.loads(response.read().decode())

        # Ensure response is well-formed
        self.assertIn("results", json_response, "Malformed response body!") 
Example #15
Source File: ipc.py    From QMusic with GNU Lesser General Public License v2.1 6 votes vote down vote up
def auth_with_policykit(action,
                        bus_name,
                        object_path,
                        interface_name,
                        interactive=1, ):
    system_bus = dbus.SystemBus()
    obj = system_bus.get_object(bus_name, object_path, interface_name)

    policykit = dbus.Interface(obj, interface_name)
    pid = os.getpid()

    subject = ('unix-process', {'pid': dbus.UInt32(pid,
                                                   variant_level=1),
                                'start-time': dbus.UInt64(0), })
    details = {'': ''}
    flags = dbus.UInt32(interactive)
    cancel_id = ''
    (ok, notused, details) = policykit.CheckAuthorization(
        subject, action, details, flags, cancel_id)

    return ok 
Example #16
Source File: test_restful.py    From keylime with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def test_023_agent_keys_vkey_post(self):
        """Test agent's POST /v2/keys/vkey Interface"""
        # CV should do this (during CV POST/PUT test)
        # Running this test might hide problems with the CV sending the V key
        global public_key

        self.assertIsNotNone(self.V, "Required value not set.  Previous step may have failed?")
        self.assertIsNotNone(public_key, "Required value not set.  Previous step may have failed?")

        encrypted_V = crypto.rsa_encrypt(crypto.rsa_import_pubkey(public_key),str(self.V))
        b64_encrypted_V = base64.b64encode(encrypted_V)
        data = {
                  'encrypted_key': b64_encrypted_V
                }
        v_json_message = json.dumps(data)

        params = f"/v{self.api_version}/keys/vkey"
        response = httpclient_requests.request("POST", "%s"%tenant_templ.cloudagent_ip,tenant_templ.cloudagent_port, params=params, data=v_json_message)
        self.assertEqual(response.status, 200, "Non-successful Agent vkey post return code!")
        json_response = json.loads(response.read().decode())


        # Ensure response is well-formed
        self.assertIn("results", json_response, "Malformed response body!") 
Example #17
Source File: gatt_linux.py    From gatt-python with MIT License 6 votes vote down vote up
def __init__(self, service, path, uuid):
        # TODO: Don't require `path` parameter, it can be calculated from service's path and uuid
        self.service = service
        self.uuid = uuid
        self._path = path
        self._bus = service._bus
        self._object_manager = service._object_manager
        self._object = self._bus.get_object('org.bluez', self._path)
        self._properties = dbus.Interface(self._object, "org.freedesktop.DBus.Properties")
        self._properties_signal = None

        descriptor_regex = re.compile(self._path + '/desc[0-9abcdef]{4}$')
        self.descriptors = [
            Descriptor(self, desc[0], desc[1]['org.bluez.GattDescriptor1']['UUID'])
            for desc in self._object_manager.GetManagedObjects().items()
            if descriptor_regex.match(desc[0])
        ] 
Example #18
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 #19
Source File: bt-audio.py    From bt-audio with GNU General Public License v3.0 6 votes vote down vote up
def __init__(self):

        self.bus = dbus.SystemBus()
        self.adapters = {}


        self.bus.add_signal_receiver(self._interfaceAdded, dbus_interface='org.freedesktop.DBus.ObjectManager', signal_name = "InterfacesAdded")
        self.bus.add_signal_receiver(self._interfaceRemoved, dbus_interface='org.freedesktop.DBus.ObjectManager', signal_name = "InterfacesRemoved")
        self.bus.add_signal_receiver(self._propertiesChanged, dbus_interface='org.freedesktop.DBus.Properties', signal_name = "PropertiesChanged", path_keyword = "path")

        # Find the adapters and create the objects
        obj_mgr = dbus.Interface(self.bus.get_object("org.bluez", "/"), 'org.freedesktop.DBus.ObjectManager')
        objs = obj_mgr.GetManagedObjects()
        for obj_path in objs:
            obj = objs[obj_path]
            if 'org.bluez.Adapter1' in obj:
                adapt_name = obj_path.split('/')[3]
                self.adapters[adapt_name] = Adapter(self.bus, obj_path)
                self.adapters[adapt_name].agentRegister() 
Example #20
Source File: test_restful.py    From keylime with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def test_015_reg_agent_delete(self):
        """Test registrar's DELETE /v2/agents/{UUID} Interface"""
        params = f"/v{self.api_version}/agents/{tenant_templ.agent_uuid}"
        response = httpclient_requests.request("DELETE", "%s"%(tenant_templ.registrar_ip),tenant_templ.registrar_tls_boot_port, params=params, context=tenant_templ.context)

        self.assertEqual(response.status, 200, "Non-successful Registrar Delete return code!")
        json_response = json.loads(response.read().decode())

        # Ensure response is well-formed
        self.assertIn("results", json_response, "Malformed response body!") 
Example #21
Source File: test_restful.py    From keylime with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def test_013_reg_agents_get(self):
        """Test registrar's GET /v2/agents Interface"""
        params = f"/v{self.api_version}/agents/"
        response = httpclient_requests.request("GET", "%s"%tenant_templ.registrar_ip,tenant_templ.registrar_tls_boot_port, params=params,  context=tenant_templ.context)

        self.assertEqual(response.status, 200, "Non-successful Registrar agent List return code!")
        json_response = json.loads(response.read().decode())

        # Ensure response is well-formed
        self.assertIn("results", json_response, "Malformed response body!")
        self.assertIn("uuids", json_response["results"], "Malformed response body!")

        # We registered exactly one agent so far
        self.assertEqual(1, len(json_response["results"]["uuids"]), "Incorrect system state!") 
Example #22
Source File: dbus_connection.py    From python-omxplayer-wrapper with GNU Lesser General Public License v3.0 5 votes vote down vote up
def __init__(self, bus_address, dbus_name=None):
        if dbus_name:
            self._dbus_name = dbus_name
        else:
            self._dbus_name = 'org.mpris.MediaPlayer2.omxplayer'
        self._bus = dbus.bus.BusConnection(bus_address)
        self.proxy = self._create_proxy()

        self.root_interface = dbus.Interface(self.proxy, 'org.mpris.MediaPlayer2')
        self.player_interface = dbus.Interface(self.proxy, 'org.mpris.MediaPlayer2.Player')
        self.properties_interface = dbus.Interface(self.proxy, 'org.freedesktop.DBus.Properties') 
Example #23
Source File: test_bt_bus.py    From bt-manager with GNU General Public License v3.0 5 votes vote down vote up
def setUp(self):
        patcher = mock.patch('dbus.Interface', MockDBusInterface)
        patcher.start()
        self.addCleanup(patcher.stop)
        patcher = mock.patch('dbus.SystemBus')
        patched_system_bus = patcher.start()
        self.addCleanup(patcher.stop)
        mock_system_bus = mock.MagicMock()
        patched_system_bus.return_value = mock_system_bus
        mock_system_bus.get_object.return_value = dbus.ObjectPath('/org/bluez') 
Example #24
Source File: generictomboy.py    From gtg with GNU General Public License v3.0 5 votes vote down vote up
def __enter__(self):
            """
            Returns the Tomboy connection

            @returns: dbus.Interface
            """
            return self.tomboy 
Example #25
Source File: bluezutils.py    From DirtyTooth-RaspberryPi with GNU Affero General Public License v3.0 5 votes vote down vote up
def find_adapter_in_objects(objects, pattern=None):
	bus = dbus.SystemBus()
	for path, ifaces in objects.iteritems():
		adapter = ifaces.get(ADAPTER_INTERFACE)
		if adapter is None:
			continue
		if not pattern or pattern == adapter["Address"] or \
							path.endswith(pattern):
			obj = bus.get_object(SERVICE_NAME, path)
			return dbus.Interface(obj, ADAPTER_INTERFACE)
	raise Exception("Bluetooth adapter not found") 
Example #26
Source File: bluezutils.py    From DirtyTooth-RaspberryPi with GNU Affero General Public License v3.0 5 votes vote down vote up
def get_managed_objects():
	bus = dbus.SystemBus()
	manager = dbus.Interface(bus.get_object("org.bluez", "/"),
				"org.freedesktop.DBus.ObjectManager")
	return manager.GetManagedObjects() 
Example #27
Source File: get-lyric.py    From lyrics-crawler with MIT License 5 votes vote down vote up
def get_current_song_info():
    # kudos to jooon at stackoverflow http://stackoverflow.com/a/33923095
    session_bus = dbus.SessionBus()
    spotify_bus = session_bus.get_object('org.mpris.MediaPlayer2.spotify',
                                         '/org/mpris/MediaPlayer2')
    spotify_properties = dbus.Interface(spotify_bus,
                                        'org.freedesktop.DBus.Properties')
    metadata = spotify_properties.Get('org.mpris.MediaPlayer2.Player', 'Metadata')

    return {'artist': metadata['xesam:artist'][0], 'title': metadata['xesam:title']} 
Example #28
Source File: gtg_stress_test.py    From gtg with GNU General Public License v3.0 5 votes vote down vote up
def connect():
    # We will connect on the session bus
    bus = dbus.SessionBus()
    liste = bus.list_names()
    busname = "org.gnome.GTG"
    remote_object = bus.get_object(busname,"/org/gnome/GTG")
    return dbus.Interface(remote_object,dbus_interface="org.gnome.GTG") 
Example #29
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 #30
Source File: net.py    From QMusic with GNU Lesser General Public License v2.1 5 votes vote down vote up
def is_network_connected_by_nm():
    try:
        import dbus
        sys_bus = dbus.SystemBus()
        proxy = sys_bus.get_object("org.freedesktop.NetworkManager",
                                   "/org/freedesktop/NetworkManager")
        interface = dbus.Interface(proxy, "org.freedesktop.NetworkManager")
        return interface.state() == 70
    except Exception, e:
        return True