0

I want kill the process using a Python program in a Linux environment. i've used below code to kill the process but it doesn't work for me.

Can someone help me in this case?

Thanks in advance.

import subprocess as sp
sp.run("ps aux |grep python |awk '{print $2}' |xargs kill");

I'm not getting any error while running above code also the command was not worked in the server.

2
  • 1
    possible duplicate of stackoverflow.com/questions/89228/… Commented Jul 15, 2019 at 6:16
  • use may have to use it with sp.run(..., shell=True) Commented Jul 15, 2019 at 6:40

3 Answers 3

2

You have some ways to run system commands via a python program:

Using the os module:

import os
os.system("ps aux |grep python |awk '{print $2}' |xargs kill")

Using the subprocess module

import subprocess
proc1 = subprocess.Popen(['ps', 'aux'], stdout=subprocess.PIPE)
proc2 = subprocess.Popen(['grep', 'python'], stdin=proc1.stdout, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
proc3 = subprocess.Popen(['awk', "'{print $2}'"], stdin=proc2.stdout, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
proc4 = subprocess.Popen(['xargs', 'kill'], stdin=proc3.stdout, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
proc1.stdout.close() # Allow proc1 to receive a SIGPIPE if proc2 exits.
proc2.stdout.close() # Allow proc2 to receive a SIGPIPE if proc3 exits.
proc3.stdout.close() # Allow proc3 to receive a SIGPIPE if proc4 exits.
out, err = proc4.communicate()
Sign up to request clarification or add additional context in comments.

Comments

0

Use os.system("ps aux |grep python |awk '{print $2}' |xargs kill"):

import os

os.system("ps aux |grep python |awk '{print $2}' |xargs kill")

Check if this works for you.

2 Comments

i've tried this also, but i dont know what is happening behind. still this is not killing the process, and its not thrown an error.
Check if it requires sudo permissions? Try running it with, sudo python <script_name>.
0

Using os module you can simply run the system commands:

import  os

os.system("ps aux |grep python |awk '{print $2}' |xargs kill")

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.