1

我正在尝试paste <(zcat f1.gz) <(zcat f2.gz)使用子进程运行。这是我到目前为止所做的:

ps1 = subprocess.Popen(('zcat', 'f1.gz'), stdout=subprocess.PIPE)
ps2 = subprocess.Popen(('zcat', 'f2.gz'), stdout=subprocess.PIPE)
ps3 = subprocess.Popen('paste', stdout=subprocess.PIPE, stdin=subprocess.PIPE)

但我不确定如何为 ps3 提供 ps1.stdout 和 ps2.stdout 作为输入。如果你们能帮助我并让我知道我是否走在正确的轨道上,我将不胜感激。

4

1 回答 1

1

我的回答很大程度上受到这篇文章的启发, 允许 对问题略有不同的python 子进程进行多个输入。

基本上,一种解决方案是使用先进先出:子进程写入先进先出,而线程使用子进程写入的数据。

import subprocess
import os
import threading

#  create our fifo for data exchange between processes
os.mkfifo('my-fifo')

#  create a reader thread that consumes data from our fifo
def read_from_fifo():
    with open('my-fifo', 'rb') as fd:
        subprocess.Popen('paste', stdin=fd)
t = threading.Thread(target=read_from_fifo) 
t.start()

#  write commands output to our fifo
with open('my-fifo', 'wb') as fifo:
    for cmd in [('zcat', 'f1.gz'), ('zcat', 'f2.gz')]:
        p = subprocess.Popen(cmd, stdout=subprocess.PIPE)
        fifo.write(p.stdout.read())

t.join()  # wait that our thread has consumed all data
os.unlink('my-fifo')

于 2022-01-12T10:26:14.343 回答