Python subprocess PIPE blocking

2019-09-15 20:10发布

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)

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?

1条回答
Emotional °昔
2楼-- · 2019-09-15 20:49

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).

查看更多
登录 后发表回答