运行包含管道的命令行并将结果显示到STDOUT [英] running a command line containing Pipes and displaying result to STDOUT

查看:90
本文介绍了运行包含管道的命令行并将结果显示到STDOUT的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何从Python调用一个包含管道并捕获输出的shell命令?

How would one call a shell command from Python which contains a pipe and capture the output?

假设命令类似于:

cat file.log | tail -1

与我尝试做的Perl类似的事情是这样的:

The Perl equivalent of what I am trying to do would be something like:

my $string = `cat file.log | tail -1`;

推荐答案

使用subprocess.PIPE,如子流程docs部分:

Use a subprocess.PIPE, as explained in the subprocess docs section "Replacing shell pipeline":

import subprocess
p1 = subprocess.Popen(["cat", "file.log"], stdout=subprocess.PIPE)
p2 = subprocess.Popen(["tail", "-1"], stdin=p1.stdout, stdout=subprocess.PIPE)
p1.stdout.close()  # Allow p1 to receive a SIGPIPE if p2 exits.
output,err = p2.communicate()

或者,使用 sh模块,管道变为 查看全文

登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆