2010-06-28 57 views
1

我需要使用stdin/stdout将Python控制台程序(作为子流程)与Python进行接口。Python子流程模块 - 意外行为

C程序是多个O就越少:

tmp = 0.0; 
    printf("\ninput>>"); 
    scanf_s("%f",&tmp); 
    printf ("\ninput was: %f",tmp); 

    tmp = 0.0; 
    printf("\ninput>>"); 
    scanf_s("%f",&tmp); 
    printf ("\ninput was: %f",tmp); 

    tmp = 0.0; 
    printf("\ninput>>"); 
    scanf_s("%f",&tmp); 
    printf ("\ninput was: %f",tmp); 

使用Python子模块,我需要从这项计划中,写的东西读取数据,然后再等等看。我用下面的代码:

>>> p=subprocess.Popen(['C:\T.exe'],stdout=subprocess.PIPE,stdin=subprocess.PIPE) 
>>> o,i=communicate('123\n') 

0的输出是:

input>> 
input was: 123.000000 
input>> 
input was: 0.000000 
input>> 
input was: 0.000000 

我期望子进程上输入等待,直到另一个O,I =通信()调用。为什么它会在没有任何输入的情况下进行到程序结束?如何解决它?

+0

这在过去也曾让我咬过一次。 :) – Skurmedel 2010-06-28 09:12:59

回答

3

每个进程最多可以有一个调用communicate(),因为communicate()等子进程终止。要重复读取和写入进程的标准流,请使用Popen类的stdoutstdin属性。

+0

如果我使用p.stdout.read(10),那么在我手动关闭进程之前,python shell没有响应。那么它输出''。与.readline和.readlines一样。那可能是什么? – Halst 2010-06-28 09:27:47

+0

'read(10)'等待直到遇到EOF或读取了10个字节。我几乎没有什么经验,但你应该使用select或者后台线程来轮询和读取流。 'subprocess'文档中还有一个关于死锁的警告。 – Philipp 2010-06-28 09:33:34

+0

你的意思是什么样的“选择”? – Halst 2010-06-28 09:39:05