[Tutor] Turning multiple Popen calls into a function

Eric Brunson brunson at brunson.com
Thu Nov 1 19:30:10 CET 2007


jay wrote:
> Hello,
>
> If I have multiple Popen calls I need to make, how can I turn these 
> into a function?

Since you're only interested in the output of the last command on the 
pipeline, I don't see a reason to keep track of them all.  I'd do 
something like this:

def pipeline( *commandlist ):
    last = None
    for command in commandlist:
        last = Popen( command,
                      stdin=last.stdout if last else None,
                      stdout=PIPE )

    return last.communicate()[0]

print pipeline( ("ls", "-la", "/etc"),
                ("grep", "hosts"),
                ("awk", "{print $1}") )

returns:
lrwxrwxrwx



Hope that helps,
e.

> from subprocess import Popen, PIPE
>
> p1 = Popen(['ls', '-l', '-a', '/etc'],stdout=PIPE)
> p2 = Popen(['grep', 'hosts'], stdin=p1.stdout, stdout=PIPE)
> p3 = Popen(['awk', '{print $1}'], stdin=p2.stdout, stdout=PIPE)
> output = p3.communicate()[0]
>
> p1 = Popen(['ps', '-ef'], stdout=PIPE)
> p2 = Popen(['grep', '-v', '2348'], stdin=p1.stdout, stdout=PIPE)
> output = p2.communicate()[0]
>
> I would be sending an arbitrary number of PIPES with each function call.
>
> I'm a little stumped as to how to handle the variables.  If I have an 
> arbitrary number of PIPES, how do I declare my variables (p1, p2, p3, 
> etc...) ahead of time in the function??
>
> Thanks for any suggestions!
>
> Jay
> ------------------------------------------------------------------------
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>   



More information about the Tutor mailing list