我喜欢在Python中生成内存(临时文件)数据流。一个线程正在用数据填充流,另一个线程使用它。
在检查io -用于处理流的核心工具之后,在我看来,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"没有写到a,以后也不能读。那是我的错误吗?如何修改代码才能在内存中获得类似对象的文件?
发布于 2018-09-05 12:02:51
@dhilmathy和@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)发布于 2018-09-05 10:51:08
实际上它是书面的,但阅读是问题所在。您应该是指类io.BytesIO。您可以使用getvalue()获得值。喜欢,
import io
a = io.BytesIO()
a.write("hello".encode())
txt = a.getvalue()
txt = txt.decode("utf-8")
print(txt) https://stackoverflow.com/questions/52183096
复制相似问题