如何将多个进程的输出连接到另一个进程的输入中?

2024-09-28 17:22:36 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在编写一个脚本来执行一个进程列表,并将它们的所有输出连接到另一个进程的输入中。我已经将我的脚本压缩成一个测试用例,使用echo和cat作为实际进程的代理。在

#!/usr/bin/python

import os,subprocess

(pipeOut, pipeIn) = os.pipe()

catProcess = subprocess.Popen("/bin/cat", stdin = pipeOut)

for line in ["First line", "Last line"]:
    subprocess.call(["/bin/echo",line], stdout = pipeIn)

os.close(pipeIn)
os.close(pipeOut)

catProcess.wait()

程序按预期工作,只是对catProcess.wait()的调用挂起(可能是因为它仍在等待更多的输入)。将close_fds=True传递给Popen或{}似乎也没有帮助。在

有没有办法关闭catProcesses的stdin,使其优雅地退出?或者有别的方法来写这个程序吗?在


Tags: echo脚本closebin进程osstdinline
1条回答
网友
1楼 · 发布于 2024-09-28 17:22:36

close_fds=True传递给catProcess对我的系统有帮助。在

不需要显式地创建管道:

#!/usr/bin/python
from subprocess import Popen, PIPE, call

cat = Popen("cat", stdin=PIPE)
for line in ["First line", "Last line"]:
    call(["echo", line], stdout=cat.stdin)
cat.communicate() # close stdin, wait

相关问题 更多 >