用子进程在Python中逐行编写/读取管道

时间:2013-03-03 19:08:01

标签: python unix subprocess pipe

我有以下代码似乎可行,用于在python中使用子进程将管道链接在一起,同时逐行读取/写入它们(不使用communicate()预先)。代码只调用Unix命令(mycmd),读取其输出,然后将其写入另一个Unix命令(next_cmd)的stdin,并将最后一个命令的输出重定向到文件。

    # some unix command that uses a pipe: command "a"
    # writes to stdout and "b" reads it and writes to stdout
    mycmd = "a | b" 
    mycmd_proc = subprocess.Popen(mycmd, shell=True,
                                  stdin=sys.stdin,
                                  stdout=subprocess.PIPE,
                                  stderr=subprocess.PIPE)
    # nextCmd reads from stdin, and I'm passing it mycmd's output
    next_cmd = "nextCmd -stdin"
    output_file = open(output_filename, "w")
    next_proc = subprocess.Popen(next_cmd, shell=True,
                                  stdin=subprocess.PIPE,
                                  stdout=output_file)
    for line in iter(mycmd.stdout.readline, ''):
        # do something with line
        # ...
        # write it to next command
        next_proc.stdin.write(line)
    ### If I wanted to call another command here that passes next_proc output
    ### line by line to another command, would I need
    ### to call next_proc.communicate() first?
    next_proc.communicate()
    output_file.close()

这似乎有效,并且只在命令末尾调用communicate()

我正在尝试扩展此代码以添加另一个命令,以便您可以执行以下操作:

mycmd1 | mycmd2 | mycmd3 > some_file

含义:逐行,从Python读取mycmd1的输出,进程该行,将其提供给mycmd2,读取mycmd2的输出并逐行处理和提要它到mycmd3,然后将其输出放在some_file中。这是可能的,还是以死锁/阻塞/未刷新的缓冲区结束?请注意,我不只是将三个unix命令作为管道调用,因为我想在其间插入Python并逐行处理每个命令的输出,然后再将其提供给下一个命令。

我想避免调用通信并将所有输出加载到内存中 - 而是我想逐行解析它。感谢。

1 个答案:

答案 0 :(得分:1)

这应该处理任意数量的命令:

import sys
import subprocess

def processFirst(out):
    return out

def processSecond(out):
    return out

def processThird(out):
    return out

commands = [("a|b", processFirst), ("nextCmd -stdin", processSecond), ("thirdCmd", processThird)]

previous_output = None
for cmd,process_func in commands:
    if previous_output is None:
        stdin = sys.stdin
    else:
        stdin = subprocess.PIPE
    proc = subprocess.Popen(cmd, shell=True,
                            stdin = stdin,
                            stdout = subprocess.PIPE)
    if previous_output is not None:
        proc.stdin.write(previous_output)

    out,err = proc.communicate()
    out = process_func(out)
    previous_output = out

只需将要运行的任何命令添加到命令列表以及应处理其输出的函数。最后一个命令的输出最终将在循环结束时位于previous_output

为了避免任何死锁/缓冲/ etc问题,您只需使用proc.communicate()运行每个命令即可完成,这将返回输出(而不是像您的示例中那样直接读取它)。然后在将其运行到完成之前将其提供给下一个命令,依此类推。

编辑:刚刚注意到您不想提前使用communicate()并且您想要逐行做出反应。我会稍微编辑我的答案来解决这个问题

This answer提供了一个示例,说明如何使用select.select()无阻塞地从管道逐行读取。

以下是针对您的特定情况使用它的示例:

import sys
import subprocess
import select
import os

class LineReader(object):
    def __init__(self, fd, process_func):
        self._fd = fd
        self._buf = ''
        self._process_func = process_func
        self.next_proc = None

    def fileno(self):
        return self._fd

    def readlines(self):
        data = os.read(self._fd, 4096)
        if not data:
            # EOF
            if self.next_proc is not None:
                self.next_proc.stdin.close()
            return None
        self._buf += data
        if '\n' not in data:
            return []
        tmp = self._buf.split('\n')
        tmp_lines, self._buf = tmp[:-1], tmp[-1]
        lines = []
        for line in tmp_lines:
            lines.append(self._process_func(line))
            if self.next_proc is not None:
                self.next_proc.stdin.write("%s\n" % lines[-1])

        return lines

def processFirst(line):
    return line

def processSecond(line):
    return line

def processThird(line):
    return line

commands = [("a|b", processFirst), ("nextCmd -stdin", processSecond), ("thirdCmd", processThird)]

readers = []
previous_reader = None
for cmd,process_func in commands:
    if previous_reader is None:
        stdin = sys.stdin
    else:
        stdin = subprocess.PIPE
    proc = subprocess.Popen(cmd, shell=True,
                            stdin = stdin,
                            stdout = subprocess.PIPE)

    if previous_reader is not None:
        previous_reader.next_proc = proc

    previous_reader = LineReader(proc.stdout.fileno(), process_func)
    readers.append(previous_reader)


while readers:
    ready,_,_  = select.select(readers, [], [], 10.0)
    for stream in ready:
        lines = stream.readlines()
        if lines is None:
            readers.remove(stream)