我想使用boto3包上传一个numpy数组到S3,该包需要一个bytes对象。我想将这个numpy数组转换为字节,但由于内存限制,没有任何复制。我尝试的东西不工作,因为他们创建副本:
numpy.ndarray.tobytes
,numpy.ndarray.tostring
bytes(arr)
个io.BytesIO(arr)
个io.BytesIO(memoryview(arr))
个
numpy似乎曾经提供numpy.ndarray.getbuffer
,但在后来的版本中被弃用。
有没有一种方法可以创建一个字节视图而不复制?
1条答案
按热度按时间ggazkfy81#
您可以利用
ctypes
模块创建指向数据数组的指针,并将其转换为字节形式。字符串
至少,这似乎满足了你在对问题的评论中提出的测试。(也就是说,如果我改变了数组,我对它的看法会改变吗?).
不过,这里有几件事需要注意。第一,python bytes对象是不可变的,这意味着如果一个对象被分配给一个变量,就会产生一个副本。
型
第二,
boto3
似乎想要一个类似File的对象,至少从版本1.28.1的源代码来看是这样。调用bio = BytesIO(memory_block.raw)
会产生一个副本,这意味着我们又回到了上传的起点。上传类
下面的
ArrayUploader
类实现了一些基本的IO方法(read
、seek
、tell
)。当read
被调用时,数据 * 仍然可以从底层内存blob中复制 *,这意味着余量仍然是限制因素。但是,如果设置了读取的大小,则一次仅从内存blob复制这么多数据。boto3
如何处理从IO
对象读取的大小,我不能告诉你。型