简体   繁体   中英

Python custom readline function misses some lines

I am trying to write a readline function that requests a fixed number of bytes from ai/o device and buffers the received data and returns a single line.

The device does not have it's own readline() method, only a recv(bytes) method and hence my function.

The recv() function is just emulating the i/o device in this case and purely for testing / debugging.

The problem is the ' a ' and ' of ' is missing from the expected output which should be:

peter piper picked a peck of pickled peppers

And I can't figure out why.

buff is an array containg complete lines, and xbuff holds partial lines.

str = ''
buff = [];
xbuff = b'' 
data = b"peter\r\npiper\r\npicked\r\na\r\npeck\r\nof\r\npickled\r\npeppers"


def readline():
  global buff,xbuff
  raw = recv(10) 
  buff = (xbuff + raw).splitlines()
  xbuff = b''
  if len(raw) == 10 and not raw.endswith(b'\r\n'):
    xbuff = buff.pop()
  if len(buff) > 0:
    line = buff.pop(0)
    return line
  return b''

def recv(chrs):
    global data
    out = data[:chrs]
    data = data[chrs:]
    return out

while True:
    line = readline()
    if line:
        str += " "+line.decode()
    else:
        print(str)
        break

peter piper picked peck pickled peppers

Oops, need to append to the buffer and not replace it

buff += (xbuff + raw).splitlines()

But is this the most pythonic / efficient way of doing this ??

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM