[英]Reusing Python Bytearray/Memoryview
我試圖通過套接字接收一系列protobuf。 我不會事先知道數據量。 我正在發送大量消息 ,並且需要在收到消息時對消息進行緩沖 (以確保我收到所有消息)。 我想利用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()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.