2015-04-22 150 views
0

我正在使用Python 2.7.9版本,当我尝试从Popen进程读取一行时,它一直卡住,直到进程结束。在结束之前我如何从标准输入读取数据?Popen.communicate stdin.write卡住

如果输入是'8200'(正确的密码),那么它会打印输出。 但是,如果密码从'8200'更改,所以没有输出,为什么?

子源代码:

#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源:

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

回答

0

如果你改变你的printf到

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

,并添加冲洗

fflush (stdout); 

缓冲区被刷新。冲洗意味着即使缓冲区尚未满,数据也会被写入。我们needet添加\ n强制换行,因为直到它

proc.stdout.readline(); 

在python读取\ n我们添加了一个readline的蟒蛇会缓冲所有输入。然后,它看起来像这样:

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

这是正在发生的事情:

  1. 蟒蛇运行子
  2. 子写上 “请输入密码:\ n”
  3. 蟒蛇读取行“输入密码:“并且什么也不做
  4. python写入子程序”123“
  5. 子程序读取123
  6. 子进程将检查123是否为8200,这是错误的,将以“不可以!”回答。
  7. “不!”由python读取并用最后一行代码打印到stdout中
+0

仍然不起作用 – null

+0

请尝试添加fflush(stdout);之后printf –

+0

是的,我们正在朝..但现在的输出是: '输入密码:' 我希望它打印:“是!”或“不!”! (我添加了fflush(stdout);仅在第一个printf后) – null