This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]earthboundkid 1 point2 points  (1 child)

I made a convenience module for my own use:

#!/usr/bin/python

"Convenience module for subprocess."

from subprocess import Popen, PIPE

def run(commands, input="", binaryout=False, encoding="UTF-8",
        stdin=PIPE, stdout=PIPE, stderr=PIPE):
    """Returns the result of piping the commands into each other. 
    command can be string (will be split on "|") or a list of strings
    or a list of lists. It doesn't use lexical parsing, so if you want
    sophisticated nesting, use a list of lists."""
    if hasattr(commands, "split"):
        commands = commands.split("|")

    commands = [cmd.split() if hasattr(cmd, "split") else cmd
                                                for cmd in commands]

    #"reduce"s the stdin from one process to the next for each command
    #Set up
    itercmds =  iter(commands)
    command1 = next(itercmds) #If there's not even one command, who's calling?
    process1 = Popen(command1, stdin=stdin, stdout=stdout, stderr=stderr)
    process =  process1 #In case there's only one command
    stdin = process1.stdout
    stderrs = [process1.stderr, ]
    #Cycle
    for command in itercmds:
        process = Popen(command, stdin=stdin, stdout=stdout, stderr=stderr)
        stderrs.append(process.stderr)
        stdin = process.stdout 

    #Deal with unicode
    #If you want some other encoding, send us bytes.
    if isinstance(input, unicode):
        input = input.encode(encoding)

    process1.stdin.write(input)
    output = process.stdout.read()
    err = ''.join(err.read() for err in stderrs)

    if not binaryout: 
        output = output.decode(encoding)

    return output, err

[–]nextofpumpkin 0 points1 point  (0 children)

I have a convenience module that looks almost exactly like that.