python 子进程被 while 循环阻塞

python subprocess blocked by while loop

我想用 Python 脚本控制 C 程序。 C 程序如下所示:

#include <stdio.h>
#include <stdlib.h>

void main(){
    int num;
    do{
        printf("insert a number: \ninsert 3 to exit\n");
        scanf("%d", &num);
        switch(num){
            case 1: {printf("you pressed 1\n");break;}
            case 2: {printf("you pressed 1\n");break;}
            default:{printf("you pressed another key\n");}
        }
    }while(num!=3);
}

我的 python 脚本正在使用子进程:

   import subprocess
   p=subprocess.Popen('./Cprogram', stdin=subprocess.PIPE, stdout=subprocess.PIPE)
   p.stdin.write('1')
   p.communicate()

结果是 python shell 被光标挡在空行上。

没有 while 在 c 程序中脚本工作正常。我该如何管理它?

谢谢

p.communicate() 将 运行 直到 C 程序完成执行。由于您没有传递 3,因此您的程序尚未完成执行。也许您正在寻找类似的东西(根据塞巴斯蒂安的评论编辑):

import subprocess

p=subprocess.Popen('./Cprogram', stdin=subprocess.PIPE, stdout=subprocess.PIPE)
p.stdin.write('1\n')
p.stdin.write('3\n')
out, err = p.communicate()
print(out)