4

Program A, is a c program that endlessly, receives input in stdin, process it and output it to stdout.

I want to write program B (in python) so it will reads A's output, and feed it back with whatever is needed. Note there must be only one instance of each of those programs, so given b1 and b2 which are instances of b instead of:

$ b1 | a | b2

I need to have

$ b1 | a | b1 

The following is the diagram of the final desired result:

alt text

4

2 回答 2

7

Use the subprocess.Popen class to create a subprocess for program A. For example:

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

Now the two processes can communicate back and forth with each other via the pipes. It might also be a good idea to save the original sys.stdin and sys.stdout into other variables so that if you ever decide to terminate the subprocess, you can restore stdin and stdout to their original states (e.g. the terminal).

于 2010-12-09T04:17:44.677 回答
1

对于那些通过谷歌来到这里的人:实际上有一个非常好的使用命名管道的方法:

首先创建2个名称管道:

mkfifo pipe1
mkfifo pipe2

然后运行这个:

echo -n x | cat - pipe1 > pipe2 & cat <pipe2 > pipe1

这将导致 cat 命令一直将字母 x 相互复制。所以现在您可以随意使用自己的程序而不是 cat 来处理输入和输出。这不仅限于python。您还可以将 java 程序与 c++ 程序连接起来。

例如,如果您的程序名为 A.py 和 B.py,则初始命令将是:

echo -n x | ./A.py - pipe1 > pipe2 & ./B.py <pipe2 > pipe1
于 2013-01-22T04:46:52.010 回答