首页 > 解决方案 > Python自定义readline函数遗漏了一些行

问题描述

我正在尝试编写一个 readline 函数,它从 ai/o 设备请求固定数量的字节并缓冲接收到的数据并返回一行。

该设备没有它自己的 readline() 方法,只有一个 recv(bytes) 方法和我的函数。

在这种情况下,recv() 函数只是模拟 i/o 设备,纯粹用于测试/调试。

问题是预期输出中缺少“ a ”和“ of ”,应该是:

peter piper picked a peck of pickled peppers

我不知道为什么。

buff 是一个包含完整行的数组,而 xbuff 包含部分行。

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

标签: python

解决方案


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 ??


推荐阅读