Making a unique application using python and DBUS
No, not unique in the sense "oh, this app is a special snowflake", but unique in the sense "you can only run one copy of this application".
I tried googling for it and I always found the same answer, "use dbus, try to own the name, if it exists already, then a copy is already running".
What I could not find is one working example of this, or at least not something conveniently labeled "here is how you do a unique application using dbus and python".
So, here is how you do a unique application using dbus and python:
Supposing your application is called uRSSus (mine is):
session_bus = dbus.SessionBus() try: session_bus.get_object("org.urssus.service", "/uRSSus") # This is the second copy, make the first one show instead # TODO: implement except dbus.DBusException: # No other copy running # This will 'take' the DBUS name name = dbus.service.BusName("org.urssus.service", bus=session_bus) # Now, start your app: window=MainWindow() object = UrssusServer(window,name) : : : etc, etc
And that's it. No, it's not hard, but since the DBUS docs seem to be... rather they seem almost not to be sometimes, every little bit may help.
For our office app I have used Shared Memory. Your approach is educative too :)
Thanks :-)
There is a tiny race condition, though, but I am not sure I care about it ;-)
I was just thinking about the race myself.
Approach 1 Get Object and if fails Create Object and Launch
This has a race of an app launching between the failed get and the create
Approach 2 Create Object and Launch and if fails get object
This has a race when the app closes between the failed create and the get.
I think this isn't satisfactory of enforcing uniqueness but handling what to do when another instance is launched but maybe for your use case one of the races is acceptable. I would guess file locks, which active state's python cookbook has some examples of (some with races, some without) would be better for enforcing uniqueness.
Well, I timed the race window.
In my slowest computer it's about 0.3 msec.
Since starting two copies of the app is not catastrophic, I can live with that, even if (of course) it's not ideal.
You should do the "approach 2", i.e. just construct BusName(name, bus=session_bus) in the try...except without the get_object call. That's a standard Python idiom ("It's easier to ask forgiveness than permission", aka EAFP), and for good reason - it's simple and robust.
@Tom
But... constructing BusName doesn't fail.
@Tom
But... constructing BusName doesn't fail.
Excelente amigo!!!