Python:如何获得多个系统命令的最终输出?

时间:2013-02-20 02:35:23

标签: python subprocess

此处有很多帖子,例如:Store output of subprocess.Popen call in a string

复杂命令存在问题。例如,如果我需要从此

获取输出
  

ps -ef | grep something | wc -l <​​/ p>

子进程不会完成这项工作,因为子进程的参数是[程序名称,参数],因此不可能使用更复杂的命令(更多程序,管道等)。

有没有办法捕获多个命令链的输出?

3 个答案:

答案 0 :(得分:5)

只需将shell=True选项传递给子流程

即可
import subprocess
subprocess.check_output('ps -ef | grep something | wc -l', shell=True)

答案 1 :(得分:5)

对于使用子进程模块的无shell,干净版本,您可以使用以下示例(from the documentation):

output = `dmesg | grep hda`

变为

p1 = Popen(["dmesg"], stdout=PIPE)
p2 = Popen(["grep", "hda"], stdin=p1.stdout, stdout=PIPE)
p1.stdout.close()  # Allow p1 to receive a SIGPIPE if p2 exits.
output = p2.communicate()[0]

Python程序基本上就是shell所做的事情:它依次将每个命令的输出发送到下一个命令。这种方法的一个优点是程序员可以完全控制命令的各个标准错误输出(如果需要,可以抑制它们,记录等)。

尽管如此,我通常更愿意使用nneonneo建议的subprocess.check_output('ps -ef | grep something | wc -l', shell=True) shell-delegation方法:它是通用的,非常清晰且方便。

答案 2 :(得分:3)

那么,另一种选择只是在普通Python中实现命令的一部分。例如,

count = 0
for line in subprocess.check_output(['ps', '-ef']).split('\n'):
    if something in line: # or re.search(something, line) to use regex
        count += 1
print count