Popen.communicate\stdin.write stuck -
i'm using python version 2.7.9 , when try reading line popen process it's stuck until process ends. how can read stdin before ends?
if input '8200' (correct password) prints output. if password changed '8200' there no output, why?
subprocess source code:
#include <stdio.h> #include <stdlib.h> int main(void) { char password[10]; int num; { printf("enter 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 change printf
printf("enter password:\n");
and add flush
fflush (stdout);
the buffer flushed. flushing means data written if buffer not full yet. needet add \n force new line, because python buffer input until reads \n in
proc.stdout.readline();
in python added readline. looked 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 happening:
- python runs subprocess
- subprocess write "enter password:\n"
- python reads line "enter password:" , nothing it
- python writes "123" subprocess
- the subprocess reads 123
- the subprocess check if 123 8200, false , answer "nope!"
- "nope!" read python , printed stdout last line of code
Comments
Post a Comment