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

3p1*_*1i4 4 python subprocess

SO上有很多帖子,比如这个:subprocess.Popen的输出存储在一个字符串中

复杂命令存在问题.例如,如果我需要从中获取输出

ps -ef | grep something | wc -l

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

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

Joh*_*ooy 5

只需将shell=True选项传递给子进程即可

import subprocess
subprocess.check_output('ps -ef | grep something | wc -l', shell=True)
Run Code Online (Sandbox Code Playgroud)


Eri*_*got 5

对于使用子进程模块的无shell,干净版本,您可以使用以下示例(来自文档):

output = `dmesg | grep hda`
Run Code Online (Sandbox Code Playgroud)

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]
Run Code Online (Sandbox Code Playgroud)

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

也就是说,我通常更喜欢使用subprocess.check_output('ps -ef | grep something | wc -l', shell=True)nneonneo建议的shell-delegation方法:它是通用的,非常清晰和方便的.