0
Python - Struct module error
Did anyone ever get this error? How do you fix it? "struct.error: unpack requires a buffer of x bytes" (x is just a number of bytes)
3 odpowiedzi
+ 2
Might be helpful:
https://stackoverflow.com/questions/60376438/struct-error-unpack-requires-a-buffer-of-4-bytes
https://python.readthedocs.io/en/stable/library/struct.html
https://www.programmersought.com/article/62104325112/
https://github.com/evernote/evernote-sdk-python3/issues/27
+ 1
I didn't get any such error but you should be putting up the code that is causing the error . I just tried to reproduce it and got an error saying unpack requires a buffer of 4 bytes. Here is the code,
import struct
a=struct.pack("h", 5)
b=struct.unpack("hh", a)
And the above error seems right since i am trying to unpack the buffer into two short integer values (each of 2 bytes) , though i packed only 2 bytes .
0
Here you go:
# this is the format of my structure:
FORMAT = '5s100s36s'
FORMAT_SIZE = struct.calcsize(FORMAT)
# then i have these functions that help me transfer the data via sockets over the network and pack + unpack the data:
def build_msg(task, data, session_id=''):
return struct.pack(FORMAT, bytes(task, 'utf-8'), bytes(data, 'utf-8'), bytes(session_id, 'utf-8'))
def parse_msg(msg):
parsed_data = []
unpacked = struct.unpack(FORMAT, msg)
for part in unpacked:
parsed_data.append((part.split(b'\0', 1)[0]).decode('utf-8'))
return tuple(parsed_data)
# transportation of the messages from the client to the server, and vice versa:
def send_msg(conn, task, data, session_id=''):
conn.send(build_msg(task, data, session_id))
def recv_msg(conn):
return conn.recv(FORMAT_SIZE)