Python。与 subprocess.Popen() 子进程连续 io eschange
python 381
原文标题 :Python. Continuous io eschange with subprocess.Popen() child process
我为我在更大的应用程序中所做的事情做了一个简单的模型。
我试图弄清楚如何与 Popen 进程通信,以便它在需要时等待 io,并且用户可以提供该输入。怎么做,甚至有可能吗?
项目文件:
scanftest.c
#include <stdio.h>
int main(void) {
int x = 1;
printf("Please, enter integer to echo.\n");
scanf("%d", &x);
printf("%d\n", 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
in循环。但是正如您所看到的,即使是简单的示例也失败了。
回复
我来回复-
furas 评论
它需要两件事
- 用 \n 发送,这样 scanf 就会知道数据的结尾在哪里。
- 使用 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")
2年前