Python子流程PIPE阻止 [英] Python subprocess PIPE blocking

查看:126
本文介绍了Python子流程PIPE阻止的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

The subprocess will output several characters, and I want to send some response via stdin. The length of the output is predictable, so I wrote code like this:

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

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

However, p.stdout.read(1) doesn't return even if the process had already output more than a character. How can I make it stop blocking after reading a byte sequence of the expected length?

推荐答案

myproc可以在标准输出重定向时使用块缓冲模式,即,直到子级中的相应缓冲区,您的父Python都看不到被冲洗.请参阅解决此问题的几种方法(并点击此处的相应链接).

myproc may use a block-buffering mode when the standard output is redirected i.e., your parent Python won't see anything until the corresponding buffer in the child is flushed. See several ways to workaround it in this answer (and follow the corresponding links there).

这篇关于Python子流程PIPE阻止的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆