首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何使用io作为文件类对象在内存中生成数据流?

如何使用io作为文件类对象在内存中生成数据流?
EN

Stack Overflow用户
提问于 2018-09-05 10:38:26
回答 2查看 1.9K关注 0票数 5

我喜欢在Python中生成内存(临时文件)数据流。一个线程正在用数据填充流,另一个线程使用它。

在检查io -用于处理流的核心工具之后,在我看来,io模块是最好的选择。

所以我给我举一个简单的例子:

代码语言:javascript
复制
#!/usr/local/bin/python3
# encoding: utf-8

import io

if __name__ == '__main__':
    a = io.BytesIO()
    a.write("hello".encode())
    txt = a.read(100)
    txt = txt.decode("utf-8")
    print(txt) 

我的榜样行不通。"hello"没有写到a,以后也不能读。那是我的错误吗?如何修改代码才能在内存中获得类似对象的文件?

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2018-09-05 12:02:51

@dhilmathy和@ShadowRanger提到io.BytesIO()没有单独的读和写指针。

我通过创建一个简单的类来解决这个问题,这个类实现了一个读指针,并记住了编写的字节数。当读取字节的数量等于写入字节的数量时,文件会收缩以节省内存。

到目前为止,我的解决方案:

代码语言:javascript
复制
#!/usr/local/bin/python3
# encoding: utf-8

import io

class memoryStreamIO(io.BytesIO):
    """
    memoryStreamIO

    a in memory file like stream object 
    """

    def __init__(self):
        super().__init__()
        self._wIndex = 0
        self._rIndex = 0
        self._mutex = threading.Lock()

    def write(self, d : bytearray):
        self._mutex.acquire()
        r = super().write(d)
        self._wIndex += len(d)
        self._mutex.release()
        return r

    def read(self, n : int):
        self._mutex.acquire()
        super().seek(self._rIndex)
        r = super().read(n)
        self._rIndex += len(r)
        # now we are checking if we can
        if self._rIndex == self._wIndex:
            super().truncate(0)
            super().seek(0)
            self._rIndex = 0
            self._wIndex = 0
        self._mutex.release()
        return r

    def seek(self, n):
        self._mutex.acquire()
        self._rIndex = n
        r = super().seek(n)
        self._mutex.release()
        return r


if __name__ == '__main__':
    a = streamIO()

    a.write("hello".encode())
    txt = (a.read(100)).decode()
    print(txt)

    a.write("abc".encode())
    txt = (a.read(100)).decode()
    print(txt)
票数 3
EN

Stack Overflow用户

发布于 2018-09-05 10:51:08

实际上它是书面的,但阅读是问题所在。您应该是指类io.BytesIO。您可以使用getvalue()获得值。喜欢,

代码语言:javascript
复制
import io

a = io.BytesIO()
a.write("hello".encode())
txt = a.getvalue()
txt = txt.decode("utf-8")
print(txt) 
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/52183096

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档