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()
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: