Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python convert memoryview to string

Tags:

python

I tried to search everywhere but could not find any relevant info.

As a result of the following code:

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)

I get

['<memory at 0x0000026821801348>']

but I need strings or bytes that are inside. Any ideas how to read a memoryview object? Thank you

like image 930
Masha Avatar asked Aug 02 '17 08:08

Masha


2 Answers

A memory object can be converted to a string using .tobytes() like so:

a = memoryview(b'mystring')
print(a)  # <memory at 0x10cbebb98>
print(a.tobytes())  # 'mystring'
like image 22
mattjegan Avatar answered Sep 19 '22 11:09

mattjegan


For Python 2.7 and 3.x you can try this:

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'
like image 69
Colateral Avatar answered Sep 17 '22 11:09

Colateral