Detect if specific Python.app instance is already running
Question: I am experimenting with OS X apps written in Python and need to detect if
there is already an instance of Python.app running with certain script. The
script modifies `CFBundleName` on-the-fly from `Python` to `MyApp` to change
the app title in the menubar.

    
    
    bundle = NSBundle.mainBundle()
    info = bundle.localizedInfoDictionary() or bundle.infoDictionary()
    info['CFBundleName'] = 'MyApp'
    

If I start another instance and check `CFBundleName` of the running apps, it
will only tell me the original value, i.e. `Python`:

    
    
    for app in NSWorkspace.sharedWorkspace().runningApplications():
        bundle = NSBundle.bundleWithURL_(app.bundleURL())
        info = bundle.localizedInfoDictionary() or bundle.infoDictionary()
        name = info.get('CFBundleName')
        if name in ('Python', 'MyApp'):
            print name  # => prints Python
    

So I need to find a way to mark a Python.app instance that runs MyApp script
to be able to abort launching duplicate instances.

Is there such way?

**Update:**

Until there is a better solution, I'll be using `lockf`

    
    
    import fcntl
    lockfile = open('/tmp/myapp.lock', 'w')
    fcntl.lockf(lockfile, fcntl.LOCK_EX | fcntl.LOCK_NB)
    

**Update 2:**

Well, I still need to find my application to focus. Currently, I just loop
through all Python.app instances and focus them one by one. Normally, there is
just one, but if there are few of them it can be messy.

    
    
    from Foundation import NSWorkspace
    from Cocoa import NSApplicationActivateAllWindows, NSApplicationActivateIgnoringOtherApps
    
    try:
        import fcntl
        lockfile = open('/tmp/myapp.lock', 'w')
        fcntl.lockf(lockfile, fcntl.LOCK_EX | fcntl.LOCK_NB)
    
    except IOError as e:
        assert (e.errno, e.strerror) == (35, 'Resource temporarily unavailable')
    
        for app in NSWorkspace.sharedWorkspace().runningApplications():
            if app.bundleIdentifier() == 'org.python.python':
                app.activateWithOptions_(NSApplicationActivateAllWindows | NSApplicationActivateIgnoringOtherApps)
        exit()
    

**Update 3:**

I am going to use a pid file until a better solution comes up

    
    
    LOCK_FILE = '/tmp/myapp.lock'
    PID_FILE = '/tmp/myapp.pid'
    
    try:
        import fcntl
        # NOTE: needs to be assigned to a variable for the lock to be preserved
        lockfile = open(LOCK_FILE, 'w')
        fcntl.lockf(lockfile, fcntl.LOCK_EX | fcntl.LOCK_NB)
    
    except IOError as e:    
        try:
            with open(PID_FILE) as f:
                pid = int(f.read())
        except:
            pid = None
    
        for app in NSWorkspace.sharedWorkspace().runningApplications():
            if app.bundleIdentifier() == 'org.python.python':
                if not pid or pid == app.processIdentifier():
                    app.activateWithOptions_(NSApplicationActivateAllWindows | NSApplicationActivateIgnoringOtherApps)
        exit()
    
    from Foundation import NSProcessInfo
    info = NSProcessInfo.processInfo()
    pid = info.processIdentifier()
    with open(PID_FILE, 'w+') as f:
        f.write(str(pid))
    


Answer: There are several ways to solve this. Among them:

  * libunique - a library specifically designed for this
  * dbus - internal communications system

Many of them are described in the answers of [this
post](http://stackoverflow.com/questions/2261997/how-can-i-detect-what-other-
copy-of-python-script-is-already-running).

A recipe for unique instances is given
[here](http://code.activestate.com/recipes/474070/).

