Search code examples
pythonsubprocess

Popen.communicate\stdin.write stuck


I'm using python version 2.7.9 and when I try reading a line from a Popen process it's stuck until the process ends. How can I read from stdin before it ends?

If the input is '8200' (correct password) then it prints the output. But if the password is changed from '8200' so there is no output, why?

subprocess source code:

#include <stdio.h>
#include <stdlib.h>

int main(void)
{
    char password[10];
    int num;
    do
    {
        printf("Enter the password:");
        scanf("%s", &password);

        num = atoi(password);

        if (num == 8200)
            printf("Yes!\n");
        else
            printf("Nope!\n");
    } while (num != 8200);

    return 0;
}

Python source:

from subprocess import Popen, PIPE

proc = Popen("Project2", shell=True, stdin=PIPE,stdout=PIPE,stderr=PIPE)
#stdout_data = proc.communicate(input='8200\r\n')[0]
proc.stdin.write('123\r\n')
print proc.stdout.readline()

Solution

  • If you change your printf to

    printf("Enter the password:\n");
    

    and add a flush

    fflush (stdout);
    

    the buffer is flushed. Flushing means the data is written even if the buffer is not full yet. we needet to add a \n to force a new line, because python will buffer all input until it reads a \n in

    proc.stdout.readline();
    

    in python we added a readline. it then looked like this:

    proc = Popen("Project2", shell=True, stdin=PIPE,stdout=PIPE,stderr=PIPE)
    proc.stdout.readline()
    proc.stdin.write('123\r\n')
    print proc.stdout.readline()
    

    this is what is happening:

    1. python runs the subprocess
    2. subprocess write "Enter the password:\n"
    3. python reads the line "Enter the password:" and does nothing with it
    4. python writes "123" to the subprocess
    5. the subprocess reads 123
    6. the subprocess will check if 123 is 8200, which is false and will answer with "Nope!"
    7. "Nope!" is read by python and printed to stdout with the last line of code