我喜欢用Python生成内存(临时文件)数据流。一个线程正在用数据填充流,另一个线程正在使用它。
检查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"
未写入,之后也无法读取。那是我的错误吗?我该如何更改代码才能在内存中获取文件,如对象?
答案 0 :(得分:1)
实际上是书面的;但是阅读是个问题。您应该指的是class io.BytesIO。您可以使用var result = [];
storeResponse('someResponse');
function storeResponse(response) {
result = response; // You don't need to use window (if the var is not declared inside the function, is global by default)
}
alert(result);
获取值。就像
getvalue()
答案 1 :(得分:0)
@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)