Welcome, guest | Sign In | My Account | Store | Cart

Sometimes it is necessary to ensure that only one instance of application is running. This quite simple solution uses mutex to achieve this, and will run only on Windows platform.

Python, 37 lines
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
from win32event import CreateMutex
from win32api import CloseHandle, GetLastError
from winerror import ERROR_ALREADY_EXISTS

class singleinstance:
    """ Limits application to single instance """

    def __init__(self):
        self.mutexname = "testmutex_{D0E858DF-985E-4907-B7FB-8D732C3FC3B9}"
        self.mutex = CreateMutex(None, False, self.mutexname)
        self.lasterror = GetLastError()
    
    def aleradyrunning(self):
        return (self.lasterror == ERROR_ALREADY_EXISTS)
        
    def __del__(self):
        if self.mutex:
            CloseHandle(self.mutex)


#---------------------------------------------#
# sample usage:
#

from singleinstance import singleinstance
from sys import exit

# do this at beginnig of your application
myapp = singleinstance()

# check is another instance of same program running
if myapp.aleradyrunning():
    print "Another instance of this program is already running"
    exit(0)

# not running, safe to continue...
print "No another instance is running, can continue here"

Upon startup, application creates a named mutex that can be checked by other processes, so they can determine if mutex is already created and application is already running. It is important to create mutex as early as possible and to close it as late as possible.

Recipe is based on C++ solution described in Knowledge base article Q243953. http://support.microsoft.com/kb/243953/

As written here CreateMutex leak?:

Mutex handles are guaranteed to close when your process exits. There is no leak since you want the Mutex to be present [during the lifetime of the process] for the second application instance that is started to detect if another instance is already running.

You use CloseHandle when you no longer need the mutex or the reference to the mutex. If it is the last reference then the object is destroyed.

Reference: MSDN CreateMutex function