如何从 Python 调用包含管道的 shell 命令并捕获输出?
假设命令类似于:
cat file.log | tail -1
我想做的 Perl 等效项是这样的:
my $string = `cat file.log | tail -1`;
使用 subprocess.PIPE,如子流程文档部分中所述《更换外壳管道》 http://docs.python.org/library/subprocess.html#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 module https://github.com/amoffat/sh,管道变成函数的组合 http://amoffat.github.io/sh/#piping:
import sh
output = sh.tail(sh.cat('file.log'), '-1')
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)