redirecting output of process to a file using subprocess.Popen()

rparimi at rparimi at
Thu Jul 10 01:32:28 CEST 2008

I am trying to redirect stderr of a process to a temporary file and
then read back the contents of the file, all in the same python
script. As a simple exercise, I launched /bin/ls but this doesn't

import subprocess as proc
import tempfile
name = tempfile.NamedTemporaryFile(mode='w+b')
print 'name is '+

cmd = []
p = proc.Popen(cmd, stdout=name, stderr=proc.STDOUT, close_fds=True)
while True:
   ret = p.poll()
   if (ret is not None):
      output = name.readlines()
      print 'out = ', output

name is /tmp/tmpjz4NJY
out =  []

I tried calling flush() on the file object but this didn't help
either. Tried closing and re-opening the file, but closing the file
object results in it getting deleted. Can the above be made to work by
using tempfiles?


More information about the Python-list mailing list