Python3:使用“with”生成字节流

2024-04-24 05:44:38 发布

您现在位置:Python中文网/ 问答频道 /正文

我想做的是生成一个任意长度的字节流。原因是,我需要生成一个任意大小的文件。(对于某些背景,我尝试流式传输稀疏文件,但had trouble when the file sizes were large,因此我尝试动态生成字节。)

我一直在阅读使对象与with一起工作的文档,我正在努力使其正确。这是我尝试过的,但仍然不起作用。我想我错过了什么,但我真的不知道是什么。你知道吗

class BinaryGenerator:
    def __init__(self, size_in_mbs):
        self.size_in_mbs = size_in_mbs

    def __enter__(self):
        yield self.__bytes_generator__(self.size_in_mbs)
        pass

    def __exit__(self, exc_type, exc_val, exc_tb):
        pass

    @staticmethod
    def __bytes_generator__(mega_bytes):
        for i in range(mega_bytes * 1024):
            yield b'\x00'

def __write_size__(size):
    with open('arbitrary-{}mb.bin'.format(size), 'wb') as file:
        with BinaryGenerator(size) as binary:
            file.write(binary)


if __name__ == '__main__':
    __write_size__(1)

实际上,我将把它与Requests Streaming Uploads一起使用,但我试图用它作为一个测试,看看是否可以复制使用with打开文件时获得的二进制数据流


Tags: 文件inselfsize字节bytesdefwith
1条回答
网友
1楼 · 发布于 2024-04-24 05:44:38

记录在案

  • 当对象具有初始化和清除函数时,使用context manager。在本例中,它与文件对象一起使用。由于文件对象实现了上下文管理器协议,因此使用文件句柄退出with块将自动关闭文件。你知道吗

    with open('arbitrary-{}mb.bin'.format(size), 'wb') as fd: ...

  • a generator是(以编程方式)生成可iterable结果的函数。我们可以把它看作是一个返回多次的函数。

至于您的问题:您可以使用生成器来实现结果流,这基本上就是它们的用途:

def bytes_generator(mega_bytes):
    for i in range(mega_bytes * 1024):
        yield b'\x00'

def write_size(size):
    with open('arbitrary-{}mb.bin'.format(size), 'wb') as fd:
         for b in bytes_generator(size):
              fd.write(b)

然而,这是非常低效的,因为它一次只写一个字节。但要修复它,只需修改生成器中的分块。你知道吗

Requests显式允许通过生成器进行分块上传。你知道吗

def gen():
    yield 'hi'
    yield 'there'

requests.post('http://some.url/chunked', data=gen())

相关问题 更多 >