python将memoryview转换为字符串

时间:2017-08-02 08:11:34

标签: python

我试图到处搜索但找不到任何相关信息。

由于以下代码:

overlapped = pywintypes.OVERLAPPED()
buffer = win32file.AllocateReadBuffer(1024*4)
fullDataRead = []
hr, data = win32file.ReadFile(handle, buffer, overlapped)
n = win32file.GetOverlappedResult(handle, overlapped, 1)
read = str(data[:n])
fullDataRead.append(read)
print(fullDataRead)

我得到了

['<memory at 0x0000026821801348>']

但我需要内部的字符串或字节。有关如何阅读memoryview对象的任何想法?谢谢

2 个答案:

答案 0 :(得分:7)

memory对象可以使用.tobytes()转换为字符串,如下所示:

a = memoryview('mystring')
print(a)  # <memory at 0x10cbebb98>
print(a.tobytes())  # 'mystring'

答案 1 :(得分:0)

对于 Python 2.7 和 3.x,你可以试试这个:

a = memoryview(b'mystring')
print(a)  # <memory at 0x10cbebb98>
#for string
print(str(a,'utf8'))  # 'mystring' as UTF-8

# for bytes
print(bytes(a))  # b'mystring'