0

I have a python script that is responsible for verifying the existence of a process with its respective name, I am using the pip module pgrep, the problem is that it does not allow me to kill the processes with the kill module of pip or with the of os.kill because there are several processes that I want to kill and these are saved in list, for example

pid = [2222, 4444, 6666]

How could you kill those processes at once? since the above modules don't give me results.

Ujjwal Dash
  • 767
  • 1
  • 4
  • 8
AdrMXR
  • 25
  • 2
  • 9

2 Answers2

1

You would loop over processes using a for loop. Ideally you should send a SIGTERM before resorting to SIGKILL, because it can allow processes to exit more gracefully.

import time
import os
import signal

# send all the processes a SIGTERM
for p in pid:
    os.kill(p, signal.SIGTERM)

# give them a short time to do any cleanup
time.sleep(2)

# in case still exist - send them a SIGKILL to definitively remove them
# if they are already exited, just ignore the error and carry on
for p in pid:
    try:
        os.kill(p, signal.SIGKILL)
    except ProcessLookupError:
        pass
alani
  • 12,573
  • 2
  • 13
  • 23
0

Try this it may work

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

For more information you can refer here

Ujjwal Dash
  • 767
  • 1
  • 4
  • 8