Ir al contenido principal

Ralsina.Me — El sitio web de Roberto Alsina

Haciendo una aplicación única con python y DBUS

Lo bus­qué en google y siem­pre en­cuen­tro la mis­ma res­pues­ta, "u­sá dbus, tra­tá de to­mar el nom­bre, si ya exis­te, en­ton­ces hay una co­pia co­rrien­do­".

Lo que no pu­de en­con­trar es un ejem­plo que fun­cio­ne de es­to, o al me­nos no un ejem­plo con­ve­nien­te­men­te eti­que­ta­do "a­sí es co­mo se ha­ce una apli­ca­ción úni­ca usan­do DBUS y py­tho­n".

Así que, así es co­mo se ha­ce una apli­ca­ción úni­ca usan­do DBUS y py­tho­n:

Su­po­nien­do que tu apli­ca­ción se lla­ma uR­S­Sus (la mía se lla­ma así):

session_bus = dbus.SessionBus()
try:
    session_bus.get_object("org.urssus.service", "/uRSSus")
    # Esta es la segunda copia, hacer que se vea la primera
    # TODO: implementar
except dbus.DBusException: # No hay otra copia corriendo
    # Esto 'toma' el nombre DBUS
    name = dbus.service.BusName("org.urssus.service", bus=session_bus)
    # Ahora, empezá la aplicación:
    window=MainWindow()
    object = UrssusServer(window,name)
    :
    :
    :
    etc, etc

Y eso es to­do. No, no es di­fí­ci­l, pe­ro co­mo la do­cu­men­ta­ción de DBUS es... o me­jor di­cho co­mo la do­cu­men­ta­ción de DBUS no es, ca­da co­si­ta pue­de ayu­da­r.

Ankur / 2009-12-11 16:16:

For our office app I have used Shared Memory. Your approach is educative too :)

Roberto Alsina / 2009-12-11 16:29:

Thanks :-)

There is a tiny race condition, though, but I am not sure I care about it ;-)

Ed Page / 2009-12-11 18:32:

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.

Roberto Alsina / 2009-12-11 19:03:

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.

Tom Lynn / 2009-12-14 12:20:

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.

Roberto Alsina / 2009-12-16 20:41:

@Tom

But... constructing BusName doesn't fail.

Roberto Alsina / 2009-12-16 20:41:

@Tom

But... constructing BusName doesn't fail.

jonisar / 2012-05-11 23:11:

Excelente amigo!!!


Contents © 2000-2024 Roberto Alsina