gpt4 book ai didi

python - 将几个子流程连接在一起

转载 作者:太空狗 更新时间:2023-10-29 18:06:51 25 4
gpt4 key购买 nike

我有 5 个进程 p1,p2,...,p5,我想将一些数据写入 p1 的标准输入,将 p1 输出通过管道传输到 p2 标准输入,最后从输出中读取最终结果p5.

到目前为止我尝试了什么:

p1 = Popen(['p1'], stdin=PIPE, stdout=PIPE)
p2 = Popen(['p2'], stdin=p1.stdout, stdout=PIPE)
...
p5 = Popen(['p5'], stdin=p4.stdout, stdout=PIPE)

# write data to stdin
p1.stdin.write(indata)
p1.stdin.close()

# not sure in what order to close the pipes here, if at all

# read output
out = p5.stdout.read()
print out

最后截取的代码只是挂起,因为我一定是错误地执行了读/写操作。

我能够使用 communicate() 和两个进程工作,而无需向第一个进程提供任何输入(来自 Python 文档的示例):

output=`dmesg | grep hda`
==>
p1 = Popen(["dmesg"], stdout=PIPE)
p2 = Popen(["grep", "hda"], stdin=p1.stdout, stdout=PIPE)
p1.stdout.close() # Allow p1 to receive a SIGPIPE if p2 exits.
output = p2.communicate()[0]

但我不知道如何在不挂起解释器的情况下为第一个进程提供输入。

我也可以为此使用 bash 脚本(我已经编写并运行),但我想知道如何使用 Python 实现相同的目的。

所以,我想问一下,如何正确地完成所有这些操作,特别是在管道上以什么顺序执行读/写/关闭操作?

如果重要的话,我正在研究 64 位 Linux。

编辑:我忘了提到所有进程 p1、..p5 都会消耗给定的所有输入、处理它、写入标准输出然后终止。因此,管道中的下一个进程不应在前一个进程完成处理之前终止。

EDIT2:我知道我也可以使用

command = 'bash -c "p1 | p2 | p3 | p4 | p5"'
proc = Popen([command], shell=True)
out, err = proc.communicate(input=indata)
print out

但我的主要兴趣是了解如何仅在 python 代码中链接管道。

最佳答案

也许这可以帮助:

import sys
import tempfile
from subprocess import Popen, PIPE


cmd = [sys.executable, '-c', 'print raw_input()']

# Using a temp file to give input data to the subprocess instead of stdin.write to avoid deadlocks.
with tempfile.TemporaryFile() as f:
f.write('foobar')
f.seek(0) # Return at the start of the file so that the subprocess p1 can read what we wrote.
p1 = Popen(cmd, stdin=f, stdout=PIPE)

p2 = Popen(cmd, stdin=p1.stdout, stdout=PIPE)
p3 = Popen(cmd, stdin=p2.stdout, stdout=PIPE)

# No order needed.
p1.stdout.close()
p2.stdout.close()

# Using communicate() instead of stdout.read to avoid deadlocks.
print p3.communicate()[0]

输出:

$ python test.py
foobar

希望这可以是hepfull。

关于python - 将几个子流程连接在一起,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6341451/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com