c-Python.子流程的持续io变更.Popen()子进程



我为我在一个更大的应用程序中所做的事情创建了一个简单的模型。

我正试图弄清楚如何与Popen进程进行通信,以便它在需要时等待io,并且用户可以提供该输入。如何做到这一点,甚至可能吗?

项目文件:

scanftest.c

#include <stdio.h>
int main(void) {

int x = 1;

printf("Please, enter integer to echo.n");
scanf("%d", &x);

printf("%dn", x);

return 0;
}

minirunner.py

from subprocess import *  # run, Popen, PIPE
run("gcc -o scanftest scanftest.c", shell=True)
x = Popen("./scanftest", stdin=PIPE, stdout=PIPE, stderr=PIPE)
while True:
if x.returncode:
break
x.stdin.write(input("stdin> ").encode('utf-8'))
print(x.stdout.read().decode('utf-8'))
print("Done")

当我运行minirunner.py时,会发生以下情况:

stdin> 10

然后我按下^C,看到下面的

^CTraceback (most recent call last):
File "minirunner.py", line 14, in <module>
print(x.stdout.read().decode('utf-8'))
KeyboardInterrupt

尝试read()时似乎卡住了

与此同时,我期待并渴望这样的东西:

stdin> 10
Please, enter integer to echo.
stdin> 10
10
Done.

我可能想在循环中处理scanf。但正如你所看到的,即使是简单的例子也会失败。

它需要两件事

  1. n发送,这样scanf就会知道数据的末尾在哪里。

  2. 使用x.stdin.flush()通知缓冲区它可以发送数据。

from subprocess import *  # run, Popen, PIPE
run("gcc -o scanftest scanftest.c", shell=True)
x = Popen("./scanftest", stdin=PIPE, stdout=PIPE)
while True:
if x.returncode:
break
text = input("stdin> ") + 'n'

x.stdin.write(text.encode('utf-8'))
x.stdin.flush()
print(x.stdout.read().decode('utf-8'))
print("Done")

最新更新