How do I automatically redirect stdout and stderr when using os.popen2?

mikem76 at mikem76 at
Wed Jun 7 21:17:53 CEST 2006

Here is what I ended up doing:

si = file('/dev/null', 'r')
so = file('/dev/null', 'a+')
i,o = os.popen2('some_command_that_prints_a_lot_to_stdout')
os.dup2(so.fileno(), o.fileno())
os.dup2(si.fileno(), i.fileno())

Thanks for your help,

Grant Edwards wrote:
> On 2006-06-07, mikem76 at <mikem76 at> wrote:
> > How do I automatically redirect stdout and stderr when using os.popen2
> > to start a long running process.
> popen2 does redirect stdout to a file object.  That's the whole
> point of using it.  If you don't want a file object that's
> connected to the child's stdout, then don't use popen2.
> > If the process prints a lot of stuff to stdout it will
> > eventually stop because it runs out of buffer space. Once I
> > start reading the stdout file returned by os.popen2 then the
> > process resumes.  I know that I could just specify > /dev/null
> > when starting the process but I'd like to know if there is a
> > way to start a process using os.popen2 or some other way so
> > that all standard out and standard error goes to /dev/null or
> > some other file.
> Yes.  Fork a child process then use the standard file
> descriptor operators to open /dev/null or some other file and
> then dup those file descriptors to stdout/stderr:
> Then you can exec the program you want to run:
> This is basically identical to the method use to do I/O
> redirection in C, so any decent book on C programming under
> Unix should have a good explanation.
> Hmmm, it looks like it's simpler touse the subprocess module.
> Just open /dev/null to get a file descriptor for it, and then
> pass that to subprocess.Popen():
> --
> Grant Edwards                   grante             Yow!  I selected E5... but
>                                   at               I didn't hear "Sam the Sham
>                                  and the Pharoahs"!

More information about the Python-list mailing list