I want to make python file which opens two programs. This two programs have to get input from each other multiple times. I opened two programs and know how to give input to one program, but i don't know how to give input multiple time on one program and get output multiple time. My code is like this.
subprocess.call("/usr/bin/gcc -o p1 "+path1,shell=True)
subprocess.call("/usr/bin/gcc -o p2 "+path2,shell=True)
cmd_1 = subprocess.Popen("./p1",shell = True,stdin = subprocess.PIPE,stdout = subprocess.PIPE,stderr = subprocess.PIPE)
cmd_2 = subprocess.Popen("./p2",shell = True,stdin = subprocess.PIPE,stdout = subprocess.PIPE,stderr = subprocess.PIPE)
std_out_1 = cmd_1.stdout
std_out_2 = cmd_2.stdout
for line in std_out_1.readlines():
print(line.decode('ascii'))
for line in std_out_2.readlines():
print(line.decode('ascii'))
Now this program just get program output. I want to give input N times for each program and get output N times. So I expect my code to be like this.
give_input(n)
for i in range(n):
t_1 = get_output(t_2) //give input t_2, and get output t_1
t_2 = get_output(t_1) //give input t_1, and get output t_2
Try using
write
andcommunicate
to send data tocmd_1
andcmd_2
and get the response, see https://docs.python.org/3/library/subprocess.html#popen-constructor.To exchange messages via pipes dynamically (not tested):
It assumes that the child processes expect a line as a request and return a single character as a response.
To make it work:
p1
,p2
should disable their internalstdout
buffering (callsetvbuf(stdout, NULL, _IONBF, 0);
at the start of the program) or callfflush()
after eachprintf()
. Related: Python C program subprocess hangs at “for line in iter”p1
,p2
into$PATH
or pass a full path instead'p1'
intoPopen()
.