gpt4 book ai didi

python - 处理子进程的标准输入和标准输出

转载 作者:行者123 更新时间:2023-12-01 07:22:18 29 4
gpt4 key购买 nike

我想编写一个Python脚本来创建一个子进程,从标准输出读取并写入标准输入。写入标准输入的内容应取决于从标准输出读取的内容。

我已经尝试了几乎所有我能找到的关于 subprocess.Popen 的方法,但没有任何结果。

基本上,我想编写一个脚本,使以下c代码打印“成功”:

#include <stdio.h>
#include <stlib.h>
int main()
{
int var, inp;
for (int i = 0; i < 100; i++) {
var = rand();
printf("Please type %d:\n", var); //random var. is printed
scanf("%d", &inp); //inp == var?

if (inp != var) {
printf("you failed miserably\n");
return 0;
}
}

printf("success\n");
return 0;
}

我无法从标准输出读取数据,同时仍保持子进程处于事件状态。任务看起来很简单,但我找不到简单的解决方案。

我期望工作的Python代码:

from subprocess import *
def getNum(s): # "Please type 1234567:\t" -> "1234567"
return "".join([t for t in s if t.isdigit()])

p = Popen("./io", stdin=PIPE, stdout=PIPE) #io is the binary obtained from above c code
for i in range(100):
out = p.stdout.readline() #script deadlocks here
print( out )
inp = getNum(out)+"\n"#convert out into desired inp
p.stdin.write(inp)
print (p.communicate()[0]) #kill p and get last output

这种方法可能有点幼稚,但我也不明白为什么它不起作用。

最佳答案

Python 程序在等待从 stdout 接收数据时陷入困境。这可能是由于 stdout 缓冲造成的。可能有几种方法可以更改此行为,但测试此行为的一种快速方法是更改​​ C 可执行文件以在打印出随机生成的数字后立即强制执行 fflush。 C 代码如下所示:

#include <stdio.h>
#include <stdlib.h>
int main()
{
int var, inp;
for (int i = 0; i < 100; i++) {
var = rand();
printf("Please type %d:\n", var); //random var. is printed

// ADDED EXPLICIT stdout flush
fflush(stdout);

scanf("%d", &inp); //inp == var?

if (inp != var) {
printf("you failed miserably\n");
return 0;
}
}

printf("success\n");
return 0;
}

通过这一更改,原始 python 脚本能够驱动整个交互。

关于python - 处理子进程的标准输入和标准输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57640352/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com