3

Within a python script I need to launch a command such as

kill $(ps aux | grep httpd | awk '{print $2}')

Using subprocess I have tried to split the command using a function from https://stackoverflow.com/a/29755431/1355628)

The function is fine with simple commands with pipe but unfortunately with the one above it does not seem to work (the return code seems to be completely random...)

Thanks is advance

Romain G
  • 63
  • 2
  • 7
  • What's your end goal here, do you want to kill a running process using python ? – iamauser Dec 29 '17 at 14:40
  • I need to handle multiple ways to stop a process. Sometimes a simple "service xxx stop" is fine but for some processes it is not enough (kill needed) – Romain G Dec 29 '17 at 14:45

1 Answers1

5

subprocess.run takes an optional shell=True argument, which will run your command in a subshell. Please do read the Security Considerations however, if you're handling user input.

Another (better, imo) solution, would be to use the psutil package and os.kill, like this:

import psutil
processes = [p for p in psutil.pids() if 'httpd' in psutil.Process(p).name()]
for process in processes:
    os.kill(...)
iCart
  • 2,179
  • 3
  • 27
  • 36
  • I have tried something like : `cmd = "kill $(ps aux | grep proces[s] | awk '{print $2}');rm -f /var/lock/process && service process start" pop = subprocess.Popen(cmd, stderr=subprocess.STDOUT, stdout=subprocess.PIPE, shell=True) pop.wait() print "return code is : %d" % pop.returncode` Executing the command in a bash is fine, but within python it results in a failure : "return code is -15" (instead of 0) – Romain G Dec 29 '17 at 15:21