运行包含管道的命令行并将结果显示到 STDOUT [英] running a command line containing Pipes and displaying result to STDOUT
本文介绍了运行包含管道的命令行并将结果显示到 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`;
推荐答案
使用子流程.PIPE,如子流程文档部分 "替换外壳管道":
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()
import sh
output = sh.tail(sh.cat('file.log'), '-1')
这篇关于运行包含管道的命令行并将结果显示到 STDOUT的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文