【问题标题】:How to use pipes in python without blocking?如何在python中使用管道而不阻塞?
【发布时间】:2010-11-24 08:02:45
【问题描述】:

在python中,我想创建一个子进程并将数据读写到它的stdio。 假设我有以下 C 程序,它只是将其输入写入其输出。

#include <stdio.h>
int main() {
    char c;
    for(;;) {
        scanf("%c", &c);
        printf("%c", c);
    }
}

在 python 中,我应该能够使用 subprocess 模块来使用它。像这样的:

from subprocess import *
pipe = Popen("thing", stdin=PIPE, stdout=PIPE)
pipe.stdin.write("blah blah blah")
text = pipe.stdout.read(4) # text should == "blah"

但是在这种情况下,读取的调用会无限期地阻塞。 我该如何做我想要实现的目标?

【问题讨论】:

    标签: python pipe subprocess popen


    【解决方案1】:

    stdout 在写入终端时是行缓冲的,但在写入管道时是完全缓冲的,因此不会立即看到您的输出。

    要刷新缓冲区,请在每个 printf() 之后调用 fflush(stdout);。另请参阅 this question,除了您的子进程是用 C 编写的之外,它是相同的,以及 this question 它引用了 C99 中定义的标准输入/标准输出行为。

    【讨论】:

      【解决方案2】:

      我找到了 pexpect 模块,它完全符合我的需要。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2016-06-05
        • 2010-09-15
        • 1970-01-01
        • 2010-12-16
        • 2012-11-11
        • 1970-01-01
        • 2011-12-05
        相关资源
        最近更新 更多