[Twisted-Python] How to emulate Python's getoutput function

Drake Smith drakesmith at adelphia.net
Fri Oct 7 22:08:13 MDT 2005


At 02:40 PM 10/8/2005 +1100, you wrote:
>On 10/8/05, Drake Smith <drakesmith at adelphia.net> wrote:
> > Is there a relatively simple way to emulate the following python function:
> >    commands.getoutput ('ifconfig eth0 | grep inet'))
> >
> > I can get halfway there with:
> >    utils.getProcessOutput ('/sbin/ifconfig', ['eth0'])
> > but the trick to piping that output to another command such as grep is
> > eluding me. Thank you.
>
>make the command "sh", and the arguments ['-c', 'shell string']. Of
>course, this means you're opening yourself up to shell insertion
>attacks if you put any user-input into that shell string.
>
>
>--
>   Twisted   |  Christopher Armstrong: International Man of Twistery
>    Radix    |    -- http://radix.twistedmatrix.com
>             |  Release Manager, Twisted Project
>   \\\V///   |    -- http://twistedmatrix.com
>    |o O|    |
>w----v----w-+
>
>
>From: Jp Calderone <exarkun at divmod.com>
>
>For the particular case of grep, this is pretty straightfoward:
>   def gotOutput(output):
>      lines = output.splitlines()
>      for L in lines:
>      if 'inet' in L:
>         yield L
>   utils.getProcessOutput(...).addCallback(gotOutput).addCallback(something)
>
>For the general case of chaining processes, you need to get down to 
>reactor.spawnProcess(). This API lets you specify which file descriptors 
>are connected to what. A pipe ends up being just that - use os.pipe() to 
>create one, hand one end to the stdout of one process and the other end to 
>the stdin of another, and now they're talking :)
>
>Hope this helps,
>
>Jp

Thank you Christopher and JP for your answers. They both work like a charm 
and I can use both techniques in my current project.





More information about the Twisted-Python mailing list