IPython - 管道多个子进程并将最后一个的结果显示到标准输出

IPython - pipe multiple subprocesses and show result of final one to stdout

有很多与此相关的问题,但 none 似乎适用于我的情况: 1- 2- 3- 4- 5-

我想要完成的是等同于 ./my_executable | rev | rev 的东西(我意识到这最终与 ./my_executable 相同,但是我需要这样做),但是使用 IPython.

我正在运行执行以下一系列命令:

p1 = subprocess.Popen("rev", stdin=subprocess.PIPE)
p2 = subprocess.Popen("rev", stdout=p1.stdin, stdin=subprocess.PIPE) 
subprocess.Popen("my_executable", stdout=p2.stdin)

我没有得到任何输出。

因为我没有为 p1.stdout 指定任何参数,所以我假设它会输出 到我 运行ning IPython 所在的航站楼。事实上,如果我这样做

p1 = subprocess.Popen("rev", stdin=subprocess.PIPE)
subprocess.Popen("my_executable", stdout=p1.stdin)

它会输出到终端。

因此,我认为我的管道从 p2 到 p1 有问题。但是,当我 运行 以下一系列命令时

f = open("test", "w")
p1 = subprocess.Popen("rev", stdout=f, stdin=subprocess.PIPE)
p2 = subprocess.Popen("rev", stdout=p1.stdin, stdin=subprocess.PIPE) 
subprocess.Popen("my_executable", stdout=p2.stdin)
f.close()

然后在终端中执行 cat test 一切正常,看来我正在正确使用管道。

为什么第一个例子没有输出到终端?

我找到的解决办法是关闭进程的stdin:

p1 = subprocess.Popen("rev", stdin=subprocess.PIPE)
p2 = subprocess.Popen("rev", stdout=p1.stdin, stdin=subprocess.PIPE) 
subprocess.Popen("my_executable", stdout=p2.stdin)
p2.stdin.close()

关闭标准输入后,p1 将输出其标准输出。