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

2
  • This is a duplicate of stackoverflow.com/questions/15080500/… Commented Feb 8, 2023 at 11:19
  • Additionally to answers, you also can use killall command to kill all processes matching executable name. Commented Feb 8, 2023 at 11:49

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.