【问题标题】:Is it possible to delete the bytes io.BytesIO after they've been read from memory?从内存中读取字节 io.BytesIO 后是否可以删除它们?
【发布时间】:2020-06-22 11:01:04
【问题描述】:

我想使用 io 中的 BytesIO 类来创建数据流,但如果我通过它管道大量数据,它会占用大量内存,所以我想问是否可以释放“旧”使用的内存“我已经读过的数据。

如果 io 模块无法做到这一点,我愿意接受其他解决方案来解决我的问题。

这是它现在的实现方式:

def __init__():
        self.audio: av.container.InputContainer = av.open(
            stream, "r", timeout=8, options=options, format="webm"
        )
        self.audio_stream: av.audio.stream.AudioStream = self.audio.streams.get(
            audio=0
        )[0]

        self.output_buffer: io.BytesIO = io.BytesIO(b"")
        self.output_container: av.container.OutputContainer = av.open(
            self.output_buffer, "w", format="opus"
        )

        self.output_stream: av.audio.stream.AudioStream = self.output_container.add_stream(
            "libopus", 48000
        )

...


def fill(self):
    position = 0
    for packet in self.audio.demux(self.audio_stream):
        packet: av.Packet
        position += packet.duration
        self.output_buffer.seek(0, 2)
        self.output_container.mux_one(packet)

...

# then you can read from the buffer with
b = self.output_buffer.read(bytes_to_read)
# this should be Opus Encoded Audio data in bytes format

提前谢谢你!

【问题讨论】:

  • 您能展示您如何将数据传送到该对象吗?这样我们就可以为您提供最适合您用例的答案
  • @C.Nivs 我觉得这个表述有点奇怪,我现在只使用io_bytes_object.write(data)
  • 但是这些数据是从哪里来的呢?这将决定答案是什么
  • 它来自解复用后的音频流,来自 PyAV 库(它是一个 libav 包装器)。
  • 好的,你能在你的问题中加入一些代码来展示(以最小的方式)数据是如何生成并放入BytesIO对象的吗?

标签: python file stream


【解决方案1】:

对于仍在阅读的每个人,我找到了一个适合我的解决方案。 使用 python 的 os 模块,您可以创建一个新管道 (os.pipe()),它会为您处理所有这些任务。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-24
    • 1970-01-01
    • 1970-01-01
    • 2020-08-07
    • 2013-12-08
    • 1970-01-01
    相关资源
    最近更新 更多