python-3.x - 如何将数据写入 Python shell 管道中第一个进程的标准输入?

标签 python-3.x subprocess posix pipeline

在围绕 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/

相关文章:

Python - 在二维列表中查找所有偶数的总和

python - 如果我们仍然需要检查每个项目,哈希的含义是什么?

python-3.x - Ubuntu 上的 Pycharm 默认解释器和 tmp 工作目录

python:获取实际环境变量进行修改并传递给子进程

python - 带引号的子进程命令不起作用

c - 使用 dlopen 访问 POSIX 函数

python3通过分隔符将大文件分割成小文件(不是大小,行)

python - 如何在 python 中一次将多个文件从本地服务器移动到 HDFS?

linux - linux下如何添加posix hooks?

c - 如何在C中保存字符串的最后一个字符?