python - 运行包含管道的命令行并将结果显示到 STDOUT

标签 python command-line pipe

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

假设命令类似于:

cat file.log | tail -1

Perl 相当于我正在尝试做的事情是这样的:

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

最佳答案

使用 subprocess.PIPE,如子流程文档部分 "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 ,管道变为 composition of functions :

import sh
output = sh.tail(sh.cat('file.log'), '-1')

关于python - 运行包含管道的命令行并将结果显示到 STDOUT,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7353054/

相关文章:

c - setbuf 只影响 stdio 调用,而不影响系统调用?

python - Tkinter 密码系统

python - 返回 Python 中顶级目录的路径 : Comparing two solutions

python - 将 Dagster 与 Django 集成

python - 如何hstack几个稀疏矩阵(特征矩阵)?

linux - 使用 linux 命令行识别文件中具有 2 个字段的重复行

shell - 如何在 macOS 上一行生成并复制 SSH key ?

c - C语言中的pipe 2 linux命令

c管道为什么是fd[0]和fd[1] 3和4

bash - 你如何使用命令启动 Unix screen 命令?