Determining if Another Instance of a Script Is Already Running in Windows
Credit: Bill Bell
Problem
In a Win32 environment, you want to ensure that only one instance of a script is running at any given time.
Solution
Many tricks can be used to avoid starting multiple copies of an
application, but they’re all quite
fragile—except those based on a mutual-exclusion (mutex)
kernel object, such as this one. Mark Hammond’s
precious win32all package supplies all the needed hooks
into the Windows APIs to let us exploit a mutex for this purpose:
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:
# Take appropriate action, as this is the second
# instance of this script; for example:
print 'Oh! dear, I exist already.'
exit(1)
else:
# This is the only instance of the script; let
# it do its normal work. For example:
from time import sleep
for i in range(10):
print "I'm running",i
sleep(1)
print "I'm done"Discussion
The string 'A unique mutex name' must be chosen to
be unique to this script, but it should not be dynamically generated,
as it must be the same for all potential simultaneous instances of
the same script. A fresh,
globally unique ID generated at
script-authoring time would be a good choice. According to the
Windows documentation, the string can contain any characters except
backslashes (\). On Windows platforms ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access