我试图通过套接字接收一系列protobuf。我不会事先知道数据量。我正在发送大量的邮件,并且在收到它们时需要buffer the messages(以确保我收到所有邮件)。我想利用Python中可用的bytearray / memoryview消除不必要的副本。

我目前正在使用字符串,并在收到数据时附加数据。这很容易,我可以通过执行以下操作来“下移”“缓冲区”:

# Create the buffer
str_buffer = []

# Get some data and add it to our "buffer"
str_buffer += "Hello World"

# Do something with the data . . .

# "shift"/offset the message by the data we processed
str_buffer = str_buffer[6:]


是否可以使用bytearray / memoryview做类似的事情?

# Create the buffer/memoryarray
buffer = bytearray(1024)
view   = memoryview(buffer)

# I can set a single byte
view[0] = 'a'

# I can "offset" the view by the data we processed, but doing this
# shrinks the view by 3 bytes. Doing this multiple times eventually shrinks
# the view to 0.
view = view[3:]


当我尝试向末尾添加更多数据时,就会出现问题。如果我曾经“偏移”现有视图,那么视图的大小将“缩小”,并且我可以添加越来越少的数据。无论如何,有没有要重用现有的memoryview并将数据向左移动?

*根据文档,我知道我无法调整数组的大小。我认为缩小的幻想对我来说是一种误解。

最佳答案

老实说,您真的不需要事先知道要期待多少数据,只需继续阅读直到没有更多数据为止:

import socket, sys

HOST = 'localhost'        # The remote host
PORT = 50007              # The same port as used by the server

recvbuff = bytearray(16)
recvview = memoryview(recvbuff)

size = 0

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((HOST, PORT))
while True:
    nbytes = s.recv_into(recvview)
    if not nbytes:
        break
    size += nbytes
    recvview = recvview[nbytes:]
    if not len(recvview):
        print "filled a chunk", recvbuff
        recvview = memoryview(recvbuff)

print 'end of data', recvbuff[:len(recvview)], size

s.close()

关于python - 重用Python Bytearray/Memoryview,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/22827794/

10-12 18:14