往返于2个Python子进程的循环管道

沙申克舍

我需要有关子流程模块的帮助。这个问题听起来似乎很重复,而且我已经以多种方式看到了许多与之相关的文章。但是即使这样我也无法解决我的问题。它如下:
我有一个C程序2.c,它的内容如下:

#include<stdio.h>
int main()
{
int a;
scanf("%d",&a);
while(1)
  {
   if(a==0)               //Specific case for the first input
     {
      printf("%d\n",(a+1));
      break;
     }
   scanf("%d",&a);
   printf("%d\n",a);
  }
return 0;
}

我需要编写一个python脚本,该脚本首先使用subprocess.call()编译代码,然后使用Popen打开两个进程以执行相应的C程序。现在,第一个过程的输出必须是第二个过程的输入,反之亦然。因此,从本质上讲,如果我的初始输入为0,则第一个过程输出2,第二个过程将其输出。依次输出3,依此类推。

下面的脚本是我的初衷,但这是有缺陷的。如果有人可以帮助我,我将非常感谢。

from subprocess import *
call(["gcc","2.c"])
a = Popen(["./a.out"],stdin=PIPE,stdout=PIPE) #Initiating Process
a.stdin.write('0')
temp = a.communicate()[0]
print temp
b = Popen(["./a.out"],stdin=PIPE,stdout=PIPE) #The 2 processes in question
c = Popen(["./a.out"],stdin=PIPE,stdout=PIPE)
while True:
    b.stdin.write(str(temp))
    temp = b.communicate()[0]
    print temp
    c.stdin.write(str(temp))
    temp = c.communicate()[0]
    print temp
a.wait()
b.wait()
c.wait()
让·弗朗索瓦·法布尔

问题在这里

while True:
    b.stdin.write(str(temp))
    temp = b.communicate()[0]
    print temp
    c.stdin.write(str(temp))
    temp = c.communicate()[0]
    print temp

一旦communicate返回,它不会引起更多注意。您必须再次运行该过程。另外,您不需要同时打开2个进程。

另外,init阶段与运行阶段没有什么不同,不同之处在于您提供了输入数据。

您可以做些什么来简化并使其工作:

from subprocess import *
call(["gcc","2.c"])
temp = str(0)

while True:
    b = Popen(["./a.out"],stdin=PIPE,stdout=PIPE) #The 2 processes in question
    b.stdin.write(temp)
    temp = b.communicate()[0]
    print temp
    b.wait()

另外,要查看2个进程并行运行,证明可以做到这一点,只需按以下步骤修复循环(通过Popen在循环中移动调用)即可:

while True:

    b = Popen(["./a.out"],stdin=PIPE,stdout=PIPE) #The 2 processes in question
    c = Popen(["./a.out"],stdin=PIPE,stdout=PIPE)

    b.stdin.write(str(temp))
    temp = b.communicate()[0]
    print temp
    c.stdin.write(str(temp))
    temp = c.communicate()[0]
    print temp

更好。b输出提供c输入:

while True:

    b = Popen(["./a.out"],stdin=PIPE,stdout=PIPE) #The 2 processes in question
    c = Popen(["./a.out"],stdin=b.stdout,stdout=PIPE)

    b.stdin.write(str(temp))
    temp = c.communicate()[0]
    print temp

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章