L. K.
L. K.

Reputation: 139

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?

Upvotes: 0

Views: 254

Answers (2)

BPL
BPL

Reputation: 9863

Here's another working solution:

[func() for func in [proc.kill for proc in psutil.process_iter() if proc.name()=="processname"][1:]]

Upvotes: 0

Serge Ballesta
Serge Ballesta

Reputation: 148900

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()

Upvotes: 1

Related Questions