subprocess -popen - reading stdout from child - hangs

Karthik Gurusamy kar1107 at gmail.com
Mon Sep 24 22:42:59 EDT 2007


On Sep 24, 2:22 pm, "gregpin... at gmail.com" <gregpin... at gmail.com>
wrote:
> On Sep 23, 2:58 am, Karthik Gurusamy <kar1... at gmail.com> wrote:
>
> > On Sep 22, 8:28 pm, "gregpin... at gmail.com" <gregpin... at gmail.com>
> > wrote:
>
> > > Let's say I have this Python file called loop.py:
>
> > > 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'
hi
>>>

BUT you may want to re-think your design. Note that your caller
process will anyway stop reading  further from your loop.py process
the moment it sees the "first" EOF. So even if you enable loop.py 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 loop.py then you
can't do it if loop.py 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.

Karthik

>
> Thanks,
>
> Greg





More information about the Python-list mailing list