简体   繁体   English

Python自定义readline函数遗漏了一些行

[英]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. 我正在尝试编写一个readline函数,该函数从ai / o设备请求固定数量的字节,并缓冲接收到的数据并返回一行。

The device does not have it's own readline() method, only a recv(bytes) method and hence my function. 该设备没有它自己的readline()方法,只有一个recv(bytes)方法,因此没有我的功能。

The recv() function is just emulating the i/o device in this case and purely for testing / debugging. 在这种情况下,recv()函数仅模拟I / O设备,纯粹用于测试/调试。

The problem is the ' a ' and ' of ' is missing from the expected output which should be: 问题是预期输出中应该缺少“ a ”和“ of ”:

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

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 ?? 但这是最pythonic /最有效的方法吗?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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