Python subprocess module - unexpected behavior
I need to interface a C console program (as subprocess) with Python using stdin/stdout.
the C program is more o less it:
tmp = 0.0;
printf("\ninput>>");
scanf_s("%f",&tmp);
printf ("\ninput was: %f",tmp);
tmp = 0.0;
printf("\ninput>>");
scanf_s("%f",&tmp);
printf ("\ninput was: %f",tmp);
tmp = 0.0;
printf("\ninput>>");
scanf_s("%f",&tmp);
printf ("\ninput was: %f",tmp);
Using python subprocess module I need to read data from this program, the write something, then read again and so on. I used the following code:
>>> p=subprocess.Popen(['C:\T.exe'],stdout=subprocess.PIPE,stdin=subprocess.PIPE)
>>> o,i=communicate('123\n')
the output of o is:
input>>
input was: 123.000000
input>>
input was: 0.000000
input>>
input was: 0.0000开发者_JAVA百科00
I would expect the subprocess to wait on input until another o,i=communicate() call. Why it is proceding to the end of the program without any input? how to fix it?
There can be at most one call to communicate()
for each process, because communicate()
waits for the child process to terminate. To repeatedly read and write from/to a process's standard streams, use the stdout
and stdin
attributes of the Popen
class.
精彩评论