[Tutor] Turning multiple Popen calls into a function

jay titleistfour at gmail.com
Thu Nov 1 19:58:14 CET 2007


Eric and Eric :-)

Thanks both for the suggestions!  I learned from each!
I believe the small function will work for me.  Its simple since I don't
have to track each pipe I open with a variable.  I had no idea I could do
that nifty if/then for the stdin, that makes it so easy. :-)

Thanks again!

Jay

On 11/1/07, Eric Brunson <brunson at brunson.com> wrote:
>
> 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
> >
>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20071101/5a273e1a/attachment-0001.htm 


More information about the Tutor mailing list