简体   繁体   English

关闭stdin之前的Python子进程Popen readline

[英]Python subprocess Popen readline before closing stdin

import subprocess as sp

p = sp.Popen("/bin/cat", stdin=sp.PIPE, stdout=sp.PIPE)

p.stdin.write(b"foobaz!\n")
p.stdin.close()
print(p.stdout.readline())

This code works as expected (cat echoes the stdin, and we can read the stdout)此代码按预期工作(猫回显标准输入,我们可以读取标准输出)

If we comment out the p.stdin.close() , the .readline() blocks indefinitely.如果我们注释掉p.stdin.close().readline()无限期地阻塞。 This behaves the same calling .read(1) instead.这与调用.read(1)行为相同。 Is there a way to readline using the subprocess module without sending EOF to stdin?有没有办法使用 subprocess 模块读取行而不将 EOF 发送到 stdin?

I am aware there are other libraries that might solve my problem, and am looking into them as well.我知道还有其他库可以解决我的问题,我也在研究它们。 For this question, I am only curious if subprocess has this capability, and how to achieve it through subprocess .对于这个问题,我只是好奇subprocess是否有这个能力,以及如何通过subprocess来实现它。

The problem is with the buffering.问题在于缓冲。 You can use bufsize=1 if you also use universal_newlines=True (though you would then write strings instead of bytes):如果您还使用universal_newlines=True则可以使用bufsize=1 (尽管您随后会写入字符串而不是字节):

p = sp.Popen("/bin/cat", stdin=sp.PIPE, stdout=sp.PIPE, 
             bufsize=1, universal_newlines=True)
p.stdin.write("foobaz!\n")
print(p.stdout.readline())

The above is tested in Python 3.5.2.以上是在 Python 3.5.2 中测试的。 Note - I have separately just read an answer to unrelated question that suggests that in more recent Python versions text=True is equivalent of universal_newlines=True , but don't have a more recent installation to try it with at time of writing.注意 - 我已经单独阅读了一个不相关问题的答案,该答案表明在更新的 Python 版本中text=True等效于universal_newlines=True ,但在撰写本文时没有更新的安装来尝试它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM