如何让这两个进程(程序)直接使用管道相互通信?

Tzu*_*hay 4 python stdin stdout pipe stdio

程序A,是无休止的ac程序,在stdin中接收输入,处理它并输出到stdout.

我想编写程序B(在python中),因此它将读取A的输出,并将其反馈给任何需要的东西.注意,每个程序必须只有一个实例,所以给定b1和b2是b的实例而不是:

$ b1 | a | b2
Run Code Online (Sandbox Code Playgroud)

我需要

$ b1 | a | b1 
Run Code Online (Sandbox Code Playgroud)

以下是最终期望结果的图表:

替代文字

Ada*_*eld 6

使用subprocess.Popen该类为程序A创建子进程.例如:

import subprocess
import sys

# Create subprocess with pipes for stdin and stdout
progA = subprocess.Popen("a", stdin=subprocess.PIPE, stdout=subprocess.PIPE)

# Reassign the pipes to our stdin and stdout
sys.stdin = progA.stdout
sys.stdout = progA.stdin
Run Code Online (Sandbox Code Playgroud)

现在,这两个进程可以通过管道相互通信.它也可能是一个好主意,保存原始sys.stdinsys.stdout到其它变量,如果你决定终止子,你可以stdin和stdout恢复到原来的状态(例如终端).

  • 我将跳过赋值sys.std*,直接使用progA.stdout和ProgA.stdin对象.这样你就不会失去标准输出. (3认同)
  • @Winston Ewert:我同意,这可能是更好的选择,但由于OP花时间制作这么好的图表,他可能有充分的理由想要重新分配stdin和stdout. (2认同)