子流程中的多个管道

2024-07-08 09:42:02 发布

您现在位置:Python中文网/ 问答频道 /正文

我尝试在ruffus管道中使用Sailfish,它以多个fastq文件作为参数。我使用python中的subprocess模块执行Sailfish,但是subprocess调用中的<()即使在我设置shell=True时也不起作用。在

这是我想用python执行的命令:

sailfish quant [options] -1 <(cat sample1a.fastq sample1b.fastq) -2 <(cat sample2a.fastq sample2b.fastq) -o [output_file]

或者(最好):

^{pr2}$

概括如下:

someprogram <(someprocess) <(someprocess)

我该如何用python来实现这一点呢?子流程是正确的方法吗?在


Tags: 模块文件命令true参数管道shellfastq
2条回答

虽然J.F.Sebastian使用命名管道提供了一个答案,但是可以使用匿名管道来实现这一点。在

import shlex
from subprocess import Popen, PIPE

inputcmd0 = "zcat hello.gz" # gzipped file containing "hello"
inputcmd1 = "zcat world.gz" # gzipped file containing "world"

def get_filename(file_):
    return "/dev/fd/{}".format(file_.fileno())

def get_stdout_fds(*processes):
    return tuple(p.stdout.fileno() for p in processes)

# setup producer processes
inputproc0 = Popen(shlex.split(inputcmd0), stdout=PIPE)
inputproc1 = Popen(shlex.split(inputcmd1), stdout=PIPE)

# setup consumer process
# pass input processes pipes by "filename" eg. /dev/fd/5
cmd = "cat {file0} {file1}".format(file0=get_filename(inputproc0.stdout), 
    file1=get_filename(inputproc1.stdout))
print("command is:", cmd)
# pass_fds argument tells Popen to let the child process inherit the pipe's fds
someprogram = Popen(shlex.split(cmd), stdout=PIPE, 
    pass_fds=get_stdout_fds(inputproc0, inputproc1))

output, error = someprogram.communicate()

for p in [inputproc0, inputproc1, someprogram]:
    p.wait()

assert output == b"hello\nworld\n"

要模拟bash process substitution,请执行以下操作:

#!/usr/bin/env python
from subprocess import check_call

check_call('someprogram <(someprocess) <(anotherprocess)',
           shell=True, executable='/bin/bash')

在Python中,可以使用命名管道:

^{pr2}$

其中named_pipes(n)是:

import os
import shutil
import tempfile
from contextlib import contextmanager

@contextmanager
def named_pipes(n=1):
    dirname = tempfile.mkdtemp()
    try:
        paths = [os.path.join(dirname, 'named_pipe' + str(i)) for i in range(n)]
        for path in paths:
            os.mkfifo(path)
        yield paths
    finally:
        shutil.rmtree(dirname)

实现bash进程替换的另一种更可取的方法(无需在磁盘上创建命名条目)是使用/dev/fd/N文件名(如果它们可用)作为suggested by @Dunes。在FreeBSD上,^{} (^{}) creates entries for all file descriptors opened by the process。要测试可用性,请运行:

$ test -r /dev/fd/3 3</dev/null && echo /dev/fd is available

如果失败,请尝试将/dev/fd符号链接到^{},就像在某些linux上那样:

$ ln -s /proc/self/fd /dev/fd

下面是/dev/fd基于someprogram <(someprocess) <(anotherprocess)bash命令的实现:

#!/usr/bin/env python3
from contextlib import ExitStack
from subprocess import CalledProcessError, Popen, PIPE

def kill(process):
    if process.poll() is None: # still running
        process.kill()

with ExitStack() as stack: # for proper cleanup
    processes = []
    for command in [['someprocess'], ['anotherprocess']]:  # start child processes
        processes.append(stack.enter_context(Popen(command, stdout=PIPE)))
        stack.callback(kill, processes[-1]) # kill on someprogram exit

    fds = [p.stdout.fileno() for p in processes]
    someprogram = stack.enter_context(
        Popen(['someprogram'] + ['/dev/fd/%d' % fd for fd in fds], pass_fds=fds))
    for p in processes: # close pipes in the parent
        p.stdout.close()
# exit stack: wait for processes
if someprogram.returncode != 0: # errors shouldn't go unnoticed
   raise CalledProcessError(someprogram.returncode, someprogram.args)

注意:在我的Ubuntu机器上,subprocess代码只在python3.4+中工作,尽管pass_fds在python3.2之后就可用了。在

相关问题 更多 >

    热门问题