我正在做一些套接字 IO,并使用 bytearray 对象作为缓冲区。我想使用 csock.recv_into 接收带有偏移量的数据,如下所示,以避免创建中间字符串对象。不幸的是,似乎不能以这种方式使用字节数组,并且下面的代码不起作用。
buf = bytearray(b" " * toread)
read = 0
while(toread):
nbytes = csock.recv_into(buf[read:],toread)
toread -= nbytes
read += nbytes
所以我使用下面的代码,它确实使用了一个临时字符串(并且有效)......
buf = bytearray(b" " * toread)
read = 0
while(toread):
tmp = csock.recv(toread)
nbytes = len(tmp)
buf[read:] = tmp
toread -= nbytes
read += nbytes
有没有更优雅的方法来做到这一点,不需要复制中间字符串?