nonblocking read()

Jp Calderone exarkun at
Tue Nov 16 03:04:15 CET 2004

On Mon, 15 Nov 2004 16:08:00 -0800, Peter Ammon <peter_ammon at> wrote:
>I would like to read from a pipe in which data may arrive slowly.  From 
> experimenting, it looks like will block until it returns the 
> maximum amount of data you asked for, in the second parameter to read(), 
> or until it hits EOF.  I cannot find a way to return only the data that 
> the file object has immediately available.
> If no data is available, blocking is OK.
> The only workaround I can think of is to call select() in a loop, 
> reading and storing one byte each time, and then returning them when 
> select() indicates that the pipe is not ready for reading.
> Are there better approaches?  Thanks,

  You can read all available bytes (up to the given limit, n) like this (taken from Twisted):

    def setNonBlocking(fd):
        """Make a fd non-blocking."""
        flags = fcntl.fcntl(fd, FCNTL.F_GETFL)
        flags = flags | os.O_NONBLOCK
        fcntl.fcntl(fd, FCNTL.F_SETFL, flags)

  Calling, n) after passing fd to setNonBlocking will return between 1 and n bytes, or raise an exception if no bytes are available.


More information about the Python-list mailing list