在围绕 Python 子进程管道的讨论中,我看到这段代码片段被大量引用。必填链接: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"
并且只有 "abc\n"
应该在 output
中被捕获。
将数据写入p1.stdin
的最佳方式是什么?我知道 subprocess.Popen.communicate()
的 input
参数,但它在管道中不起作用。此外,该解决方案需要正确处理阻塞。
我的猜测:对 communicate()
背后的代码进行逆向工程,并为这个特定问题创建另一个版本。在我这样做之前,我想问一下是否有我不知道的更简单的解决方案。
最佳答案
写入p1.stdin
,然后在调用p2.communicate()
之前关闭它:
In [1]: import subprocess
In [2]: %cpaste
Pasting code; enter '--' alone on the line to stop or use Ctrl-D.
:p1 = subprocess.Popen(['cat'],
: stdin=subprocess.PIPE,
: stdout=subprocess.PIPE)
:p2 = subprocess.Popen(['head', '-n', '1'],
: stdin=p1.stdout,
: stdout=subprocess.PIPE)
:p1.stdout.close()
:--
In [3]: p1.stdin.write(b'This is the first line.\n')
Out[3]: 24
In [4]: p1.stdin.write(b'And here is the second line.\n')
Out[4]: 29
In [5]: p1.stdin.close()
In [6]: p2.communicate()
Out[6]: (b'This is the first line.\n', None)
(不要忘记发送给 cat
的数据中的换行符,否则它将无法工作。)
关于python-3.x - 如何将数据写入 Python shell 管道中第一个进程的标准输入?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30695670/