Reputation: 111
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
Upvotes: 2
Views: 141
Reputation: 2654
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
Upvotes: 1
Reputation: 87221
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(...)
.
Upvotes: 0