本文介绍了运行包含管道的命令行并将结果显示到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()
import sh
output = sh.tail(sh.cat('file.log'), '-1')
这篇关于运行包含管道的命令行并将结果显示到STDOUT的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!