Skip to content

Instantly share code, notes, and snippets.

@ciiqr
Forked from noamraph/activate_app_if_running.py
Last active August 29, 2015 14:03
Show Gist options
  • Save ciiqr/1fcfe4082c5bc87aaac1 to your computer and use it in GitHub Desktop.
Save ciiqr/1fcfe4082c5bc87aaac1 to your computer and use it in GitHub Desktop.
Run or Raise using DBus
"""
Allow an application to activate a running instance of itself instead of
starting another instance.
"""
## Usage ##
# import sys
# APP_ID = "com.example.application"
# if activate_if_already_running(APP_ID):
# sys.exit(0)
#
# def activateHandler():
# print "I was activated!"
# listen_for_activation(APP_ID, activateHandler)
import dbus.service
from dbus.mainloop.glib import DBusGMainLoop
def listen_for_activation(app_id, activateHandler):
"""
Listen for 'activate' events. If one is sent, call 'activate'.
"""
class DBUSService(dbus.service.Object):
def __init__(self, activateHandler):
self.activateHandler = activateHandler
bus_name = dbus.service.BusName(app_id, bus=dbus.SessionBus())
dbus.service.Object.__init__(self, bus_name, '/' + app_id.replace('.', '/'))
@dbus.service.method(app_id)
def activate(self):
self.activateHandler()
DBusGMainLoop(set_as_default=True)
_myservice = DBUSService(activateHandler)
def activate_if_already_running(app_id, appName):
"""
Activate the existing application if it's already running. Return True if found
an existing application, and False otherwise.
"""
bus = dbus.SessionBus()
try:
programinstance = bus.get_object(app_id, '/' + app_id.replace('.', '/'))
activate = programinstance.get_dbus_method('activate', app_id)
except dbus.exceptions.DBusException:
return False
else:
print "An existing instance of " + appName + " is already running. Activating it."
activate()
return True
finally:
bus.close()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment