Reputation: 93
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.
Upvotes: 0
Views: 686
Reputation: 69745
You have some ways to run system commands via a python program:
import os
os.system("ps aux |grep python |awk '{print $2}' |xargs kill")
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()
Upvotes: 2
Reputation: 41
Using os module you can simply run the system commands:
import os
os.system("ps aux |grep python |awk '{print $2}' |xargs kill")
Upvotes: 0
Reputation: 244
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.
Upvotes: 0