代码之家  ›  专栏  ›  技术社区  ›  Stefan Jaritz

如何使用io将内存中的数据流生成为类似文件的对象?

  •  0
  • Stefan Jaritz  · 技术社区  · 8 年前

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

    检查后 io - Core tools for working with streams ,在我看来 io

    #!/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" 不是写给一个也不能读后。我的错误是什么?我必须如何修改代码才能在内存中获得类似文件的对象?

    2 回复  |  直到 8 年前
        1
  •  3
  •   Stefan Jaritz    7 年前

    @迪尔马蒂和@ShadowRanger提到了这一点 io.BytesIO()

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

    #!/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)
    
        2
  •  2
  •   dhilmathy    8 年前

    实际上,它是书面的,但阅读是个问题。你应该指的是 class io.BytesIO . 您可以使用 getvalue() . 比如,

    import io
    
    a = io.BytesIO()
    a.write("hello".encode())
    txt = a.getvalue()
    txt = txt.decode("utf-8")
    print(txt)