#13 method to read up to N bytes without blocking

closed
nobody
None
5
2009-07-21
2008-08-04
No

I'd like to be able to read up to N bytes without blocking from a serial device. ie read everything in the buffer (up to a limit), only.

The current read() method reads exactly N bytes, unless there is a timeout.

The os.read(N) call actually does this, returning up to N bytes without blocking. The wrapper logic in the read() method means this isn't exposed to the user though.

One workaround is to use dev.read(dev.inWaiting()), but that causes one extra system call than necessary.

At other times I'd like to block then read everything that came in, but not necessarily block until I have all of the specified number of bytes.

I've added a readany() method to my local copy of serialposix which shows what I mean; it might not be the best general solution though.

def readany(self, size=128, block=False):
"""Read any available bytes on the serial port, up to size bytes.
If no bytes are immediately available it will block until the timeout is
exceeded (if block is True)."""
if self.fd is None: raise portNotOpenError
if size > 0:
if block:
ready,_,_ = select.select([self.fd],[],[], self._timeout)
if not ready:
return ''
return os.read(self.fd, size)

It'll read up to size bytes, optionally blocking until there's any available. (It has the same EOF bug I just logged about separately.)

thanks
Hamish

Discussion

  • Chris Liechti

    Chris Liechti - 2009-07-21
    • status: open --> closed
     
  • Chris Liechti

    Chris Liechti - 2009-07-21

    opening the port with timeout=0 and then using read with an arbitrary number should also give the desired behavior

     

Log in to post a comment.