Skip to content

Instantly share code, notes, and snippets.

@justinmklam
Created July 29, 2020 14:40
Show Gist options
  • Save justinmklam/d8d1c60678827fc4d3943c548cf4d1c2 to your computer and use it in GitHub Desktop.
Save justinmklam/d8d1c60678827fc4d3943c548cf4d1c2 to your computer and use it in GitHub Desktop.
Faster implementation of pyserial's readline. Source: https://github.com/pyserial/pyserial/issues/216#issuecomment-369414522
#!/usr/bin/python3
class ReadLine:
def __init__(self, s):
self.buf = bytearray()
self.s = s
def readline(self):
i = self.buf.find(b"\n")
if i >= 0:
r = self.buf[:i+1]
self.buf = self.buf[i+1:]
return r
while True:
i = max(1, min(2048, self.s.in_waiting))
data = self.s.read(i)
i = data.find(b"\n")
if i >= 0:
r = self.buf + data[:i+1]
self.buf[0:] = data[i+1:]
return r
else:
self.buf.extend(data)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment