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

2
  • What's your end goal here, do you want to kill a running process using python ? Commented Dec 29, 2017 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) Commented Dec 29, 2017 at 14:45

1 Answer 1

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(...)
Sign up to request clarification or add additional context in comments.

1 Comment

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)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.