Search code examples
pythonprocessos.systemtaskkill

How to make a program close it's currently running instance upon startup?


I have a command line program which I'd like to keep running until I open it again, so basically a program which first checks if there's currently any already running instance of itself and kill it.

I tried os.system('TASKKILL /F /IM program.exe') but it turned out to be stupid because it also kills itself.


Solution

  • Because my working stations don't have access to internet and installing packages is a mess, I ended up coming up with this solution:

    import os
    
    os.system('tasklist > location/tasks.txt')
    with open('location/tasks.txt', 'r') as pslist:
        for line in pslist:
            if line.startswith('python.exe'):
                if line.split()[1] != str(os.getpid()):
                    os.system(f'TASKKILL /F /PID {line.split()[1]}')
                    break
    os.remove('location/tasks.txt')
    

    It prints the output of the tasklist command to a file and then checks the file to see if there's a runnig python process with a different PID from it's own.

    edit: Figured out I can do it with popen so it's shorter and there are no files involved:

    import os
    
    for line in os.popen('tasklist').readlines():
        if line.startswith('python.exe'):
            if line.split()[1] != str(os.getpid()):
                os.system(f'taskkill /F /PID {line.split()[1]}')
                break