popen2 results

Steven Howe howe.steven at gmail.com
Wed Apr 25 18:31:00 CEST 2007


Robert Rawlins - Think Blue wrote:
> Hello guys,
>
>  
>
> I've recently ported my application from bash to python, however there are
> still a few bash line utilities I -have- to use in the application as there
> isn't any alternative available to me. In the old days of bash I would have
> grep'd the output from these commands to determine the outcome.
>
>  
>
> I'm now using popen2 to run the command which works a charm, but I'm
> struggling to parse the results of the function, has anyone had any
> experience with this? I've found a few suggested solutions dotted around,
> such as this one.
>
>  
>
>      import os
>
>  
>
>      def filtered(command, source):
>
>          dest, result = os.popen2(command)
>
>          dest.write(source)
>
>          dest.close()
>
>          try:
>
>               return result.read()
>
>          finally:
>
>               result.close()
>
>  
>
> But to be honest I'm struggling to get it to do anything as it doesn't
> states what the 'source' object is or should be.
>
>  
>
> Thanks for any help guys, I'm just looking to capture the output from the
> command and then I can go about a little REGEX on it.
>
>  
>
> Thanks,
>
>  
>
> Rob
>
>
>   
check out os.popen3 as well. An Example? Let's assume you were doing 'ls 
-1', which at the
console would give you a one column list of files (and yes, I know I can 
use glob.glob for this;
this is an example).

    from os import popen3
    ( sin, sout, serr ) = popen3( 'ls -1 /tmp' )
    fList = sout.readlines()
    for f in fList:
        print f
    errors = serr.readlines()
    for line in errors:
        print line


Now you have 3 file handles.
sin: input (which I've never used, as I give popen3 a complete command)
sout: the standard output stream
serr: the standard error output
You can read sout and serr and take action on them.
Oh and each line has a '\n' linefeed (probably '\r\n' on Windows). 
Depending on what your doing
with the output, you might want to use string.strip to eliminate the 
linefeeds.

sph
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20070425/719bddca/attachment.html>


More information about the Python-list mailing list