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.

lmiguelvargasf
  • 40,464
  • 32
  • 169
  • 172
prem Rexx
  • 67
  • 6

3 Answers3

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()
lmiguelvargasf
  • 40,464
  • 32
  • 169
  • 172
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.

Nitin
  • 216
  • 1
  • 7
  • 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. – prem Rexx Jul 15 '19 at 06:23
  • Check if it requires `sudo` permissions? Try running it with, `sudo python `. – Nitin Jul 15 '19 at 06:32
0

Using os module you can simply run the system commands:

import  os

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