subprocess -popen - reading stdout from child - hangs

Karthik Gurusamy kar1107 at
Tue Sep 25 04:42:59 CEST 2007

On Sep 24, 2:22 pm, "gregpin... at" <gregpin... at>
> On Sep 23, 2:58 am, Karthik Gurusamy <kar1... at> wrote:
> > On Sep 22, 8:28 pm, "gregpin... at" <gregpin... at>
> > wrote:
> > > Let's say I have this Python file called
> > > import sys
> > > print 'hi'
> > > sys.stdout.flush()
> > Add sys.stdout.close()
> Adding sys.stdout.close() and removing sys.stdout.flush() seems to
> make it work.  But can the while loop still use sys.stdout later on?
> Do I have to reopen it?

Once you close a file-object, you cannot use it. You'll get exception
if you try.
I quickly tried the fdopen on id 1 (stdout in unix like OS) and it
seems to work

>>> import sys
>>> sys.stdout.close()
>>> import os
>>> print 'hi'
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: I/O operation on closed file
>>> sys.stdout=os.fdopen(1, 'w')
>>> print 'hi'

BUT you may want to re-think your design. Note that your caller
process will anyway stop reading  further from your process
the moment it sees the "first" EOF. So even if you enable to
generate more output (thru' the above fdopen), the caller process is
not going to see the newly generated data.

If your requirement is to collect all output from then you
can't do it if has an infinite loop across its data generation
points (ie it can generate data after the infinite loop -- which
anyway doesn't sense).

If all you want is not to get blocked, try one of the select solutions
or read a small amount at a time (which you can guarantee to be
available). Yet another solution would be you could set up an alarm
and get out of the blocking read if the alarm fires.


> Thanks,
> Greg

More information about the Python-list mailing list