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:
ready,_,_ = select.select([self.fd],,, self._timeout)
if not ready:
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.)
Log in to post a comment.