Execute A Bash Command With Parameter In Python
Solution 1:
You're mixing opening and closing quotations and you pass a colon by mistake on your other attempts among other things.
Try this for a fix:
pid = subprocess.call("ps -ef | grep app | awk -v n=" + str(count) + " NR==n | awk '{print $2}'", shell=True)
You opened the command parameter with "
and there for you need to close it before you do + str()
with a "
and not a '
. Further more i swapped the , 'NR=
with + "NR=
since you want to append more to your command and not pass a argument to subprocess.call()
.
As pointed out in the comments, there's no point in splitting the command with shlex
since piping commands isn't implemented in subprocess
, I would however like to point out that using shell=True
is usually not recommended because for instance one of the examples given here.
Solution 2:
An other vay is using format:
pid = subprocess.call("ps -ef | grep app | awk -v n={} NR==n | awk '{{print $2}}'".format(str(count)), shell=True)
Solution 3:
Your Awk pipeline could be simplified a great deal - if the goal is to print the last match, ps -ef | awk '/app/ { p=$2 } END { print p }'
does that. But many times, running Awk from Python is just silly, and performing the filtering in Python is convenient and easy, as well as obviously more efficient (you save not only the Awk process, but also the pesky shell=True
).
for p in subprocess.check_output(['ps', '-ef']).split('\n'):
if'app' in p:
pid = p.split()[1]
Post a Comment for "Execute A Bash Command With Parameter In Python"