如何多次将子进程stdin用于一个程序

时间:2016-05-09 00:33:11

标签: python subprocess

我早期的问题是这样的:How to give input multiple times to another program on python

我的项目是制作N时间囚徒困境游戏,我想使用C代码制作的两个代码在一个python程序中使用。

对于每一场比赛,我想得到两个项目的输出,并给出结果(如果一个说实话而另一个没有,一个告诉将是无辜的,另一个谁不会得到3年监禁生活...这样的事情)两个程序,并重复N次。

所以我制作了像这样的python代码和C代码

1。 C代码

#include <stdio.h>
int n;
int result;
int main(){
    scanf("%d",&n);
    printf("1");
    for(int i=2;i<=n;i++){
        scanf("%d",&result);
        if(result==1) printf("1"); // 0 means another person remain silent, 1 means another person says truth.
        else printf("0");
    }
    return 0;
}

2。 Python代码

subprocess.call("/usr/bin/gcc -o p1 "+path,shell=True)
subprocess.call("/usr/bin/gcc -o p2 "+path,shell=True)
cmd_1 = subprocess.Popen("./p1",shell = True,stdin = subprocess.PIPE,stdout = subprocess.PIPE,stderr = subprocess.PIPE)
cmd_2 = subprocess.Popen("./p2",shell = True,stdin = subprocess.PIPE,stdout = subprocess.PIPE,stderr = subprocess.PIPE)
cmd_1.stdin.write(bytes('10\n','utf-8'))
cmd_2.stdin.write(bytes('10\n','utf-8'))
for i in range(10):
    cmd1_stdout, cmd1_stderr = cmd_1.communicate()
    cmd2_stdout, cmd2_stderr = cmd_2.communicate()
    for line in cmd1_stdout:
        print('result for p_1 : ' + chr(line))
        result_1 = line
    for line in cmd2_stdout:
        print('result for p_2 : ' + chr(line))
        result_2 = line
        if(i != 9):
            cmd_1.stdin.write(bytes(chr(result_2),'utf-8'))
        if(i != 9):
            cmd_2.stdin.write(bytes(chr(result_1),'utf-8'))

但这会产生错误,结果就是这样。

错误

ValueError: write to closed file

结果

result for p_1 : 1
result for p_1 : 0
result for p_1 : 0
result for p_1 : 0
result for p_1 : 0
result for p_1 : 0
result for p_1 : 0
result for p_1 : 0
result for p_1 : 0
result for p_1 : 0
result for p_2 : 1
result for p_2 : 0
result for p_2 : 0
result for p_2 : 0
result for p_2 : 0
result for p_2 : 0
result for p_2 : 0
result for p_2 : 0
result for p_2 : 0
result for p_2 : 0

在调用cmd_1.stdin.write()之后,我认为我的C程序在得到cmd1_stdout之前关闭。

但我想让C程序在我输入N-1次之前不关闭。如何为一个程序提供多个输入?

0 个答案:

没有答案