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:
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With