如何取消单个字节对象中的多个腌制项目?

How do I unpickle multiple pickled items in a single bytes object?

This answer 解释了如何在 文件.

中解开多个项目

但是,我正在通过网络发送已腌制的对象。如果两个 pickled 对象快速连续发送,它们最终可能会读入同一个缓冲区。

如何使用 bytes 对象复制链接答案中的行为?有没有我可以拆分的明确定义的终止符,或者 "advance" bytes 对象的方法?

例如:

test = pickle.dumps("hello")
test += pickle.dumps("world")

print(pickle.loads(test)) # Prints "hello" -- how do I get "world"?

遵循链接答案中的模式,但 use io.BytesIO to make an in-memory file-like object,例如:

# Changed to receive open file-like object instead of name
def load(fileobj):
    while True:
        try:
            yield pickle.load(fileobj)
        except EOFError:
            break

test = pickle.dumps("hello")
test += pickle.dumps("world")

with io.BytesIO(test) as f:
    for obj in load(f):
        ... do stuff with obj ...