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/q243953/

6 comments

Niki Estner 15 years, 9 months ago  # | flag

Usage in a library. Maybe I didn't get something: If I put this into a library and used the library in two completely different programs, wouldn't that permit them to run at the same time? Wouldn't it make sense to include something like sys.argv[0] in the mutex name?

Mustafa Görmezer 15 years, 9 months ago  # | flag

Release Mutex. What about releasing mutex after successful work of instance ?

Dragan Jovelic (author) 15 years, 9 months ago  # | flag

Re: Usage in a library. You got it right. Mutex name given here is just example, but in real situation, it should be given according to specific needs of your application, program name (sys.argv[0]) or something else. When I first used it, I used combination of sys.argv[0] and sys.argv[1], because it was allowed to run same program at same time, but only if it is started with different arguments.

Niki Estner 15 years, 9 months ago  # | flag

Releasing the mutex. CloseHandle releases the mutex, AFAIK. And, of course, process shutdown should do so anyway.

Dragan Jovelic (author) 15 years, 9 months ago  # | flag

Re: Release Mutex. In destructor, CloseHandle is called on mutex handle and I am not sure is it necessary to call ReleaseMutex explicitly. Original solution from Microsoft also uses only CloseHandle.

I am using it like this for long time in C++ programs and now in Python and didn't experience any problems, but would appreciate further comments/suggestions about this issue.

Alexander Belchenko 11 years, 11 months ago  # | flag

The mutex object in the example above is not acquired so there is no need to "release" it.