我在使用subprocess.communicate()读取/写入子进程中的stdin/stdout时遇到问题。subprocess.communicate()发送垃圾来处理?
这是孩子的过程(在C)
#include <stdio.h>
int main()
{
char buf[128];
printf("test\n");
gets(buf);
printf("%s", buf);
return 0;
}
这是在Python程序调用的子程序
import subprocess
proc = subprocess.Popen('./test', stdin=subprocess.PIPE, stdout=subprocess.PIPE)
stdin, stderr = proc.communicate()
print stdin
proc.communicate(stdin)
stdin, stderr = proc.communicate()
print stdin
print stdin
我希望它可以打印
test
input was test:
但是,似乎proc.communicate()会为gets()导致EOF,导致子应用程序终止。无论如何,我可以在不发送EOF的情况下与子应用程序进行通信? IE我想读到应用程序,然后写信给它。
我接受了下面的答案,因为找到我的问题的解决方案非常重要。我还想补充一点,我需要一个'fflush(stdout);'作为输入被缓冲,这是导致问题。 – endeavormac 2012-02-22 20:38:49