gpt4 book ai didi

python - 多个进程异步读取同一管道

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

如何将数据从一个管道传送到三个不同的进程?

nulfp = open(os.devnull, "w")

piper = Popen([
"come command",
"some params"
], stdout = PIPE, stderr = nulfp.fileno())

pipe_consumer_1 = Popen([
"come command",
"some params"
], stdin = piper.stdout, stderr = nulfp.fileno())

pipe_consumer_2 = Popen([
"come command",
"some params"
], stdin = piper.stdout, stderr = nulfp.fileno())

pipe_consumer_3 = Popen([
"come command",
"some params"
], stdin = piper.stdout, stderr = nulfp.fileno())

pipe_consumer_1.communicate()
pipe_consumer_2.communicate()
pipe_consumer_3.communicate()
piper.communicate()

如果我运行上面的代码,它会产生一个损坏的文件。这意味着管道消费者可能不会读取管道的完整输出。

这个可以正常工作,但速度要慢得多:

nulfp = open(os.devnull, "w")

piper_1 = Popen([
"come command",
"some params"
], stdout = PIPE, stderr = nulfp.fileno())

piper_2 = Popen([
"come command",
"some params"
], stdout = PIPE, stderr = nulfp.fileno())

piper_3 = Popen([
"come command",
"some params"
], stdout = PIPE, stderr = nulfp.fileno())

pipe_consumer_1 = Popen([
"come command",
"some params"
], stdin = piper_1.stdout, stderr = nulfp.fileno())

pipe_consumer_2 = Popen([
"come command",
"some params"
], stdin = piper_2.stdout, stderr = nulfp.fileno())

pipe_consumer_3 = Popen([
"come command",
"some params"
], stdin = piper_3.stdout, stderr = nulfp.fileno())

pipe_consumer_1.communicate()
pipe_consumer_2.communicate()
pipe_consumer_3.communicate()
piper_1.communicate()
piper_2.communicate()
piper_3.communicate()

关于如何使第一个代码片段以与第二个代码片段相同的方式工作的任何建议?如果我使用第一种方法,该过程将在 1/3 的时间内完成。

最佳答案

这只使用一个字节的“ block ”,但你明白了。

from subprocess import Popen, PIPE

cat_proc = '/usr/bin/cat'

consumers = (Popen([cat_proc], stdin = PIPE, stdout = open('consumer1', 'w')),
Popen([cat_proc], stdin = PIPE, stdout = open('consumer2', 'w')),
Popen([cat_proc], stdin = PIPE, stdout = open('consumer3', 'w'))
)


with open('inputfile', 'r') as infile:
for byte in infile:
for consumer in consumers:
consumer.stdin.write(byte)

测试时,消费者输出文件与输入文件匹配。

编辑:这是从具有 1K block 的进程中读取的。

from subprocess import Popen, PIPE

cat_proc = '/usr/bin/cat'

consumers = (Popen([cat_proc], stdin = PIPE, stdout = open('consumer1', 'w')),
Popen([cat_proc], stdin = PIPE, stdout = open('consumer2', 'w')),
Popen([cat_proc], stdin = PIPE, stdout = open('consumer3', 'w'))
)

producer = Popen([cat_proc, 'inputfile'], stdout = PIPE)

while True:
byte = producer.stdout.read(1024)
if not byte: break
for consumer in consumers:
consumer.stdin.write(byte)

关于python - 多个进程异步读取同一管道,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11561201/

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