nonblocking read()

Jp Calderone exarkun at divmod.com
Mon Nov 15 21:04:15 EST 2004


On Mon, 15 Nov 2004 16:08:00 -0800, Peter Ammon <peter_ammon at rocketmail.com> wrote:
>I would like to read from a pipe in which data may arrive slowly.  From 
> experimenting, it looks like os.read() 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 os.read(fd, n) after passing fd to setNonBlocking will return between 1 and n bytes, or raise an exception if no bytes are available.

  Jp



More information about the Python-list mailing list