1

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.000000

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?

1
  • This has bitten me once in the past as well. :) Commented Jun 28, 2010 at 9:12

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

4 Comments

if i use p.stdout.read(10) then the python shell is not responding until I close the process manually. then it outputs ''. same with .readline and .readlines. What that could be?
read(10) waits until it encounters EOF or has read 10 bytes. I have little experience with that, but you should use select or background threads to poll and read from the streams. There is also a warning about deadlocks in the subprocess documentation.
what kind of "select" do you mean?
btw, p.stdin.write() works perfect. and all p.stdout.read*() works fine only after termination of the subprocess.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.