nonblocking read()

Donn Cave donn at u.washington.edu
Tue Nov 16 19:54:15 EST 2004


In article <2vvjkoF2re95sU1 at uni-berlin.de>,
 paul koelle <paul at subsignal.org> wrote:

> Peter Ammon wrote:
> 
> > Are there better approaches?  Thanks,
> 
> What is wrong with:
> 
> fp = open('foo', 'r')
> 
> while 1:
>    line = fp.readline()
>    if not line:
>      time.sleep(0.3)
>      continue
>    process(line)
> 
> ??

A couple of things are wrong with it.

The way I remember it, the question was about a
pipe, created by popen(), not open().

When fp.readline() returns '', that means that
the write end of the pipe has closed, and no
more data is forthcoming.  There's no use for
the sleep or continue above, you may simply
break from the loop at that point.

Once those issues are taken care of, of course
it's true, you can read lines from a pipe one by
one with readline().  However, the question didn't
mention lines, and instead asked about the read()
method, so you have to wonder if perhaps the data
in question is actually not line structured.  If
its structure is something other than lines (which
readline() supports), or fixed length blocks (which
read(n) supports), then I don't think you want to
use file object methods to read it.

   Donn Cave, donn at u.washington.edu



More information about the Python-list mailing list