Home > Software engineering >  Sending Python object throughth socket
Sending Python object throughth socket

Time:12-12

I have a problem that then sending a list throughth socket,
it have to be bytes-like object, and okay I can convert it
string and then do .encode("utf-8"), but the problem
here it that it is string and it is hard to rebuild it
list from string, and literal_eval() from ast library
didn't work then I have something like that:

[("Something", datetime.datetime(2021, 12, 11, 0, 0))]

And that is problem, I had to have those objects, and my
question is How to send python object without need to
convert it into a string, or like some kind of object
notation like JSON?

This can be tested on basic socket server from
Python Socket Documentation.

Literal Eval that fails:

from ast import literal_eval
new_line = literal_eval("[(2, 2.0, 'MS-0150886', 'B1A', 'MP5 TEST IS HERE!', None, None, datetime.datetime(2021, 8, 13, 0, 0), datetime.datetime(2021, 8, 13, 0, 0), 38.0, None, None, '1', None, None, None, 1.0, None, 1.0, 'KS-005418-2', 'KS-005419-1', 'SPRAWDZ 9', None, None, None, 1.0, None, None, None, None, 1.0, 1)]")
print(new_line)
print(type(new_line))

Error:

Traceback (most recent call last):
  File "C:\I deleted\this path\test.py", line 3, in <module>
    new_line = literal_eval("[(2, 2.0, 'MS-0150886', 'B1A', 'MP5 TEST IS HERE!', None, None, datetime.datetime(2021, 8, 13, 0, 0), datetime.datetime(2021, 8, 13, 0, 0), 38.0, None, None, '1', None, None, None, 1.0, None, 1.0, 'KS-005418-2', 'KS-005419-1', 'SPRAWDZ 9', None, None, None, 1.0, None, None, None, None, 1.0, 1)]")
  File "C:\Program Files\Python39\lib\ast.py", line 105, in literal_eval
    return _convert(node_or_string)
  File "C:\Program Files\Python39\lib\ast.py", line 85, in _convert
    return list(map(_convert, node.elts))
  File "C:\Program Files\Python39\lib\ast.py", line 83, in _convert
    return tuple(map(_convert, node.elts))
  File "C:\Program Files\Python39\lib\ast.py", line 104, in _convert
    return _convert_signed_num(node)
  File "C:\Program Files\Python39\lib\ast.py", line 78, in _convert_signed_num
    return _convert_num(node)
  File "C:\Program Files\Python39\lib\ast.py", line 69, in _convert_num
    _raise_malformed_node(node)
  File "C:\Program Files\Python39\lib\ast.py", line 66, in _raise_malformed_node
    raise ValueError(f'malformed node or string: {node!r}')
ValueError: malformed node or string: <ast.Call object at 0x000001B82F7CDDF0>

CodePudding user response:

Did you try pickle?

import pickle

# Client
data = [("Something", datetime.datetime(2021, 12, 11, 0, 0))]
s.sendall(pickle.dumps(data))

# Server
data = pickle.loads(conn.recv(1024))
print(data)
  • Related