Search code examples
pythonkillpsutil

Kill every python process name with psutil except one


I'm using the following python script to kill every process with the given name:

import psutil

for proc in psutil.process_iter():
    if proc.name() == "processname":
        proc.kill()

I want the script to leave one process with the given name open. How can I achieve this? Is it possibile using this method?


Solution

  • You should simply skip the first one:

    piter = psutil.process_iter()
    first = True
    for proc in psutil.process_iter():
        if proc.name() == "processname":
            if First:
                First = False
            else:
                proc.kill()