【问题标题】:Sending Python object throughth socket通过套接字发送 Python 对象
【发布时间】:2022-01-15 20:22:35
【问题描述】:

我有一个问题,然后通过套接字发送列表,
它必须是类似字节的对象,我可以转换它
字符串然后做.encode("utf-8"),但是问题
这里它是 string 并且很难重建它
从字符串中列出,从 ast 库中列出 literal_eval()
没用然后我有类似的东西:

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

这就是问题所在,我必须拥有这些对象,而我的
问题是如何发送 python 对象而不需要
将其转换为字符串,或类似某种对象
像 JSON 这样的符号?

这可以在
Python Socket Documentation 的基本套接字服务器上进行测试。

失败的文字评估:

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))

错误:

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>

【问题讨论】:

    标签: python python-3.x string sockets byte


    【解决方案1】:

    你试过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)
    

    【讨论】:

      猜你喜欢
      • 2012-03-13
      • 2019-04-21
      • 2014-01-11
      • 2021-01-11
      • 2017-04-04
      • 2014-11-13
      • 1970-01-01
      • 2012-08-29
      相关资源
      最近更新 更多