首页 > 解决方案 > 使用列表参数的子进程中的Python内部管道?

问题描述

可以创建这样的子流程...

commandlist = ['cat', '/some/file']

sp = subprocess.Popen(commandlist)

但是是否可以将该序列的输出通过管道传输到同一子进程内的另一个命令中?

例如,序列/列表等价于cat /some/file | sed 's/foo/bar/'什么?

我想避免使用字符串输入,shell=True并且想知道是否可以在不创建 2 个子进程的情况下完成。

谢谢,克里斯

标签: pythonsubprocess

解决方案


管道语法是一个 shell 结构,所以你可以使用 shell 来执行它:

sp = subprocess.Popen("cat /some/file | sed 's/foo/bar/'", shell=True)

但管道本身并不局限于外壳,因此您可以在 Python 中建立管道:

sp1 = subprocess.Popen(['cat', '/some/file'], stdout=subprocess.PIPE)
sp2 = subprocess.Popen(['sed', 's/foo/bar'], stdin=sp1.stdout)

推荐阅读