0

I'm trying to kill a specific process with a command which works well in the shell but not from python subprocess

import subprocess
subprocess.call(["kill", "$(ps | grep process | awk '{ print $1}' | head -n1)"], shell=False)

A work around would be to put this command into a shell script and run the shell script. Is it possible from python subprocess directly ?

6
  • 2
    Use shell=True? Commented Mar 19, 2021 at 10:01
  • kill $(ps | grep process | awk '{ print $1}' | head -n1)" use pkill process? Commented Mar 19, 2021 at 10:08
  • what do you mean by shell script? Commented Mar 19, 2021 at 10:11
  • @KamilCuk I cannot use pkill as not available in the yocto distribution I have Commented Mar 19, 2021 at 10:19
  • @mousetrail I tried with shell True and it was not working better Commented Mar 19, 2021 at 10:19

1 Answer 1

2
import subprocess

subprocess.Popen("kill $(ps | grep ncat | awk '{print $1}' | head -n1)", shell=True)

In your example, you don't create a subprocess from bash, but at the same time you use $(...) which is a bash instruction. To be more precise, you create a kill process and pass it argument $(...) which is not precomputed.

The above example creates a bash process, and then tells it to interpret kill $(...). Bash converts $(...) to a value, and then it runs kill VALUE.

Sign up to request clarification or add additional context in comments.

1 Comment

Yes, only one "but", but /bin/sh is not necessarily bash. It may be other Bourne shell.

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.