python - 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
解决方案
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 ??
推荐阅读
- c# - 为什么我可以在 c#7.3 中将 ref struct 声明为类的成员?
- java - 如何在 Spring Boot 中从 application.properties 文件中进行可配置的 Retryable maxAttempts 和退避
- javascript - 如何防止空白页对 http 错误做出反应
- kubernetes - Calico 的 Kubernetes DNS 和 NetworkPolicy 不起作用
- c++ - 如何获取正确的线程 ID 和值
- python - 如何更改它以使用 aq 表进行强化学习
- javascript - Firebase firestore onSnapshot - 在使用 Promise 进行初始数据查询后获取实时更新
- java - 如何以编程方式将 TextView 添加到布局中?
- angular - 为什么订阅合并的 observable 的异步管道会覆盖先前发出的值?
- c# - 如何连接MySQL数据库?这个代码库,没有错误。但不能插入数据