Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
282 views
in Technique[技术] by (71.8m points)

Execute a bash command with parameter in Python

This is a bash command that I run in python and get the expected result:

count = subprocess.Popen("ps -ef | grep app | wc -l", stdout=subprocess.PIPE, shell=True)

but when I'd like to pass an argument (count in this case) cannot figure out how to do it. I tried:

pid = subprocess.call("ps -ef | grep app | awk -v n=' + str(count), 'NR==n | awk '{print $2}'", shell=True)

and

args = shlex.split('ps -ef | grep app | awk -v n=' + str(count), 'NR==n | awk '{print $2}'')
pid = subprocess.Popen(args, stdout=subprocess.PIPE, shell=True)

among other attempts, from various posts here, but still cannot make it.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...