在Python中使用参数执行bash命令

在Python中使用参数执行bash命令

本文介绍了在Python中使用参数执行bash命令的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我在python中运行并获得预期结果的bash命令:

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)

但是当我想传递一个参数(在这种情况下为count)时,我不知道该怎么做.我试过了:

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)

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.

推荐答案

您正在混合使用引号和结束语,并且在其他尝试中误将冒号传递了.

You're mixing opening and closing quotations and you pass a colon by mistake on your other attempts among other things.

请尝试以下解决方法:

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

您使用"打开了命令参数,因此在使用" + str()进行操作之前,需要先将其关闭不是'.此外,我将,'NR = 换为 +"NR = ,因为您想向命令添加更多内容,而不是将参数传递给 subprocess.call().

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().

正如评论中指出的那样,用 shlex 拆分命令毫无意义,因为管道命令未在 subprocess 中实现,但是我想指出通常不建议使用 shell = True ,因为例如.

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.

这篇关于在Python中使用参数执行bash命令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-23 06:37