Getting a process's output [solved]

Dietrich Epp dietrich at zdome.net
Mon Jan 19 18:47:56 EST 2004


On Jan 19, 2004, at 2:13 PM, Gerrit Holl wrote:

> Dietrich Epp wrote:
>> Is there any easy way to get all the output of a process?  Ideally, 
>> the
>> function takes parameters like exec(), calls fork(), wait()s for the
>> process to complete, and returns the process's stdout, stderr, and 
>> exit
>> status.  By stdout and stderr I don't mean file objects or
>> descriptors... I mean strings containing the entire output.
>>
>> I would try to do it myself, but I'm not sure how to interleave the
>> operations.
>
> Try commands.getstatusoutput() or the various popen functions.

Thanks, although getstatusoutput requires arguments to be quoted.  I 
looked at the source code to getstatusoutput() and popen() to come up 
with a replacement which doesn't need quoted arguments and doesn't 
create a shell.  I don't think it portable, and it will undoubtedly do 
something very nasty if one of the system calls should fail.  I think 
this would be very cool in the library (the function, not its 
deficiencies).

import os
import sys

def run_process(path, args):
     out_r, out_w = os.pipe()
     pid = os.fork()
     if pid:
         os.close(out_w)
         outf = os.fdopen(out_r)
         text = outf.read()
         outf.close()
         status = os.waitpid(pid, 0)[1]
         return status, text
     else:
         try:
             if out_w != 1:
                 os.close(1)
                 os.dup2(out_w, 1)
             if out_w != 2:
                 os.close(2)
                 os.dup2(out_w, 2)
             os.close(out_w)
             os.execvp(path, args)
         finally:
             # Should be _exit
             sys.exit(1)

Blah blah blah, I hereby release the above code into the public domain. 
  Most of the time I spent trying to get the above code to work I 
thought that stdout == 0, whoops.





More information about the Python-list mailing list