Single Instance of app

Bill Bell bill-bell at bill-bell.hamilton.on.ca
Sun Aug 26 23:35:52 CEST 2001


"Al Gonzalez" <alberto at mindspring.com> wrote, in part:
> Is there a standard way in Python to determine if an instance on
> application is already running.

I dunno about standard. (Perhaps someone else will comment.) 
Here's one way:

from win32event import CreateMutex
from win32api import GetLastError
from winerror import ERROR_ALREADY_EXISTS
from sys import exit

handle = CreateMutex ( None, 1, 'A unique mutex name' )

if GetLastError ( ) == ERROR_ALREADY_EXISTS:
    print 'Oh! dear, I exist already.'
    exit ( 1 )

from time import sleep
sleep ( 20 ) # simulates process continuing

Open two DOS boxes and launch this script in each one, the 
second within 20 seconds of launching the first, and you should 
see the second instance extinguish itself.

As you have likely surmised the 'A unique mutex name' string must 
be unique to your app so that all invocations of this code try to 
open the same mutex.

Bill




More information about the Python-list mailing list