Skip to content
Advertisement

Failed to struct.pack connection name in python

I try to use struct.pack but i get the next exception when i run it:

Traceback (most recent call last):
 File "a_sdk.py", line 36, in <module>
   a.get_time(1)
 File "a_sdk.py", line 25, in get_controller_time
   self._s.connect()
 File "C:sdkss.py", line 55, in connect
    msg_connect = protocol_Connect(self.sp_name)
 File "C:sdksuntils.py", line 39, in 
    protocol_Connect
 return struct.pack(connection_struct, 4, 0, 0, 0, name_len, connect_name)
 struct.error: argument for 's' must be a bytes object

the code that i run:

def protocol_Connect(connect_name):
    name_len = len(connect_name)
    connection_struct = f'!5B{name_len}s'.encode('utf-8')
    return struct.pack(connection_struct, 4, 0, 0, 0, name_len, connect_name)

I try to send the connection_struct as str and also as a bytes using encode.

Advertisement

Answer

The {name_len}s in your connection_struct specifies that you will pass {name_len} number of chars so when you call struct.pack() the last argument is expected to be of bytes of length {name_len}

To solve the struct.error convert connect_name from type string to byte and connection_struct can be either bytes or strings:

def protocol_Connect(connect_name):
    connect_name=str.encode(connect_name)
    # or connect_name = connect_name.encode('utf-8')
    name_len = len(connect_name)
    connection_struct = f'!5B{name_len}s'
    return struct.pack(connection_struct, 4, 0, 0, 0, name_len, connect_name)
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement