Make a python script single-instance

Reverend Jim

Sometimes you want to ensure that only one copy of a script can be run at time. Windows provides a facility called a mutex and you can use it to prevent multiple instances.

To create the mutex, all I have to do is

varname = GetMutex()

If the mutex already exists then IsRunning() will return True so the line

if (myapp := GetMutex()).IsRunning():

both creates the mutex (maybe) and tests if the app is already running. Note this this uses the walrus (:=) works only in Python 3.8.2 or newer.

About the Author

I completed my Computer Science degree at the University of Manitoba in 1976. I did two and a half years of programming in medical research followed by twenty-nine years at Manitoba Hydro (electric utility). Most of that was spent on doing development and maintenance on an AGC/SCADA (real-time programming/process control) system. The last ten years of that was spent doing application and infrastructure support and development. I have programmed in FORTRAN (mostly), APL, PL/1, COBOL, Lisp, SNOBOL, ALGOL, Assembler (several flavours), C, C++, Paradox, VB, vbScript and more recently, Python. I am married with two grown children of whom I am very proud, and a most beautiful wife. I am currently retired (and loving it).



        Provides a method by which an application can ensure that only one      
        instance of it can be running at any given time.                        


        if (app := GetMutex()).IsRunning():                                     
            print("Application is already running")                             

import os
import sys

from win32event import CreateMutex
from win32api   import CloseHandle, GetLastError
from winerror   import ERROR_ALREADY_EXISTS

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

    def __init__(self):
        thisfile   = os.path.split(sys.argv[0])[-1]  = thisfile + "_{D0E858DF-985E-4907-B7FB-8D732C3FC3B9}"
        self.mutex = CreateMutex(None, False,
        self.error = GetLastError()

    def IsRunning(self):
        return (self.error == ERROR_ALREADY_EXISTS)

    def __del__(self):
        if self.mutex: CloseHandle(self.mutex)

if __name__ == "__main__":

    # check if another instance of this program is running
    if (myapp := GetMutex()).IsRunning():
        print("Another instance of this program is already running")

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

        while True: pass
    except KeyboardInterrupt: pass
Be a part of the DaniWeb community

We're a friendly, industry-focused community of 1.21 million developers, IT pros, digital marketers, and technology enthusiasts learning and sharing knowledge.