【发布时间】:2012-03-13 04:28:50
【问题描述】:
我在使用 subprocess.communicate() 的子进程中读取/写入 stdin/stdout 时遇到问题。
这是子进程(在 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);,因为输入正在被缓冲,这会导致问题。
标签: python subprocess