Search code examples
pythonprocesskillpsutil

Python - kill multiple processes in a function


I'm new to python, and have the following code working to kill processes, but it's not elegant. I have to define the process and the search for it on multiple lines .

I'm looking to create a function or a way to assign any process I add to this list, and kill all with out looking for each one. (its seems redundant )

something like assigning any new PROCESS I add, to be in a method ALL_PROC and then the for loop can iterate over it, looking for any and all processes contained in ALL_PROC

sorry if this is obvious , this is my first stack question :)

Process1 = "pro1.exe"
Process2 = "pro2.exe"
Process3 = "pro3.exe"

for proc in psutil.process_iter():  
    if proc.name() == Process1:
       proc.kill()
    if proc.name() == Process2:
       proc.kill()
    if proc.name() == Process3:
       proc.kill()

Solution

  • Use a set of names, then you can check presence with the in operator:

    processes = {'pro1.exe', 'pro2.exe', 'pro3.exe'}
    for proc in psutil.process_iter():  
        if proc.name() in processes:
           proc.kill()
    

    And if you wanted to define a set of the first n 'pro[n].exe' strings, then you could use a generator expression with the set() constructor:

    processes = set(f'pro{i}.exe' for i in range(1,n))
    

    which, with e.g. n = 10, gives:

    {'pro6.exe', 'pro8.exe', 'pro9.exe', 'pro2.exe', 'pro4.exe', 'pro3.exe', 'pro1.exe', 'pro7.exe', 'pro5.exe'}
    

    notice that a set does not have order, since it has no concept of indexes.