2

I need one help regarding killing application in linux As manual process I can use command -- ps -ef | grep "app_name" | awk '{print $2}' It will give me jobids and then I will kill using command " kill -9 jobid". I want to have python script which can do this task. I have written code as

import os
os.system("ps -ef | grep app_name | awk '{print $2}'")

this collects jobids. But it is in "int" type. so I am not able to kill the application. Can you please here? Thank you

Aakash Patel
  • 111
  • 7
  • This is a duplicate of https://stackoverflow.com/questions/15080500/how-can-i-send-a-signal-from-a-python-program – Amogh Sarpotdar Feb 08 '23 at 11:19
  • Additionally to answers, you also can use `killall` command to kill all processes matching executable name. – dimich Feb 08 '23 at 11:49

2 Answers2

1
    import subprocess
    temp = subprocess.run("ps -ef | grep 'app_name' | awk '{print $2}'", stdin=subprocess.PIPE, shell=True, stdout=subprocess.PIPE)
    job_ids = temp.stdout.decode("utf-8").strip().split("\n")
    # sample job_ids will be: ['59899', '68977', '68979']
    
    # convert them to integers
    job_ids = list(map(int, job_ids))
    # job_ids = [59899, 68977, 68979]

Then iterate through the job ids and kill them. Use os.kill()

for job_id in job_ids:
    os.kill(job_id, 9)

Subprocess.run doc - https://docs.python.org/3/library/subprocess.html#subprocess.run

Tevin Joseph K O
  • 2,574
  • 22
  • 24
0

To kill a process in Python, call os.kill(pid, sig), with sig = 9 (signal number for SIGKILL) and pid = the process ID (PID) to kill.

To get the process ID, use os.popen instead of os.system above. Alternatively, use subprocess.Popen(..., stdout=subprocess.PIPE). In both cases, call the .readline() method, and convert the return value of that to an integer with int(...).

pts
  • 80,836
  • 20
  • 110
  • 183