在socket.recv_into中使用bytearray [英] using bytearray with socket.recv_into
问题描述
我正在做一些套接字IO,并使用bytearray对象作为缓冲区.我想使用csock.recv_into接收带有偏移量的数据到此缓冲区中,如下所示,以避免创建中间字符串对象.不幸的是,似乎字节数组不能以这种方式使用,并且下面的代码不起作用.
I am doing some socket IO, and using a bytearray object as a buffer. I would like to receive data with an offset into this buffer using csock.recv_into as shown below in order to avoid creating intermediary string objects. Unfortunately, it seems bytearrays can't be used this way, and the code below doesn't work.
buf = bytearray(b" " * toread)
read = 0
while(toread):
nbytes = csock.recv_into(buf[read:],toread)
toread -= nbytes
read += nbytes
所以我改用下面的代码,确实使用一个临时字符串(并且可以工作)...
So instead I am using the code below, which does use a temporary string (and works)...
buf = bytearray(b" " * toread)
read = 0
while(toread):
tmp = csock.recv(toread)
nbytes = len(tmp)
buf[read:] = tmp
toread -= nbytes
read += nbytes
是否有一种更优雅的方法不需要复制中间字符串?
Is there a more elegant way to do this that doesn't require copying intermediate strings around?
推荐答案
使用memoryview
包裹bytearray
:
buf = bytearray(toread)
view = memoryview(buf)
while toread:
nbytes = sock.recv_into(view, toread)
view = view[nbytes:] # slicing views is cheap
toread -= nbytes
这篇关于在socket.recv_into中使用bytearray的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!