【问题标题】:Python subprocess PIPE blockingPython子进程管道阻塞
【发布时间】:2016-06-05 01:37:56
【问题描述】:

子进程会输出几个字符,我想通过标准输入发送一些响应。输出的长度是可以预测的,所以我写了这样的代码:

p = Popen("myproc", shell = True, stdin = PIPE, stdout = PIPE)
p.stdout.read(1)

但是,即使进程已经输出了多个字符,p.stdout.read(1) 也不会返回。读取预期长度的字节序列后如何使其停止阻塞?

【问题讨论】:

  • 如果可以,请使用 select 和 poll。也可以尝试使用flush()
  • 这很难做到。您最好使用pexpect 以这种方式读取/写入管道。

标签: python process pipe subprocess stdout


【解决方案1】:

myproc 可以在标准输出被重定向时使用块缓冲模式,即,在子级中的相应缓冲区被刷新之前,您的父级 Python 将看不到任何内容。见several ways to workaround it in this answer (and follow the corresponding links there)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-03-23
    • 1970-01-01
    相关资源
    最近更新 更多