[Python] Windows CreateMutexW using Python not working

Discussão em 'Python' iniciado por Stack, Julho 9, 2025.

  1. Stack

    Stack Membro Participativo

    I'm writing a Python application that connects to an external device. I want to enable the user to operate multiple devices simultaneously by running multiple instances of the application, but each device may only connect to one application instance. This calls for a mutex keyed to the device's serial number. With the help of ChatGPT, I came up with the following minimal example (without the serial number):

    import ctypes
    import sys

    ERROR_ALREADY_EXISTS = 183

    mutex = ctypes.windll.kernel32.CreateMutexW(None, 1, "my-app\\1234")
    err = ctypes.GetLastError()
    print(f'Error code received: {err}')

    if err == ERROR_ALREADY_EXISTS:
    print("Another instance is already using the device.")
    sys.exit(0)

    input("Program running. Press Enter to exit...")


    When I open two command windows and run this script in each one, neither one errors out and both give an err value of 3. I checked the Microsoft documentation for CreateMutexW and for the error codes, and I can't figure out what I'm doing wrong.

    Continue reading...

Compartilhe esta Página