【发布时间】:2015-08-22 02:58:45
【问题描述】:
在围绕 Python 子流程管道的讨论中,我看到该代码 sn-p 被大量引用。必填链接:https://docs.python.org/3.4/library/subprocess.html#replacing-shell-pipeline
稍作修改:
p1 = subprocess.Popen(['cat'],
stdin=subprocess.PIPE,
stdout=subprocess.PIPE)
p2 = subprocess.Popen(['head', '-n', '1'],
stdin=p1.stdout,
stdout=subprocess.PIPE)
# Allow p1 to receive a SIGPIPE if p2 exits.
p1.stdout.close()
output = p2.communicate()[0]
除了简洁地展示挑战之外,这个 shell 管道毫无意义。输入"abc\ndef\nghi\n",output 中只应捕获"abc\n"。
将数据写入p1.stdin 的最佳方式是什么?我知道subprocess.Popen.communicate() 的input 参数,但它在管道中不起作用。此外,解决方案需要正确处理阻塞。
我的猜测:对communicate() 背后的代码进行逆向工程,并为这个特定问题创建另一个版本。在我这样做之前,我想问一下是否有一个我不知道的更简单的解决方案。
【问题讨论】:
标签: python-3.x subprocess posix pipeline