【问题标题】:TypeError after trying to send pickled data using socket尝试使用套接字发送腌制数据后出现 TypeError
【发布时间】:2014-10-02 15:42:48
【问题描述】:

我正在尝试将图像从服务器发送到客户端,所以我想我会使用 pickle 来序列化图像。

服务器代码:

import socket
import cPickle as pickle

server_socket = socket.socket()
server_socket.bind(('127.0.0.1', 1729))

server_socket.listen(1)
(client_socket, client_address) = server_socket.accept()

client_request = client_socket.recv(1024)

if client_request == 'IMG':
    img_data =  actions.options[client_request]()
    client_socket.send(pickle.dump(img_data, -1))
else:
    client_socket.send(actions.options[client_request]())

server_socket.close()

但是当我尝试运行它时(在检查 img_data 是否正确创建之后),我得到了错误:

File "C:/py_prog/my_server.py", line 25, in <module> client_socket.send(pickle.dump(img_data, -1)) TypeError: argument must have 'write' attribute

如何更改要写入的腌制数据的属性?

【问题讨论】:

    标签: python image sockets python-2.7 pickle


    【解决方案1】:

    要获取腌制字符串,您应该使用pickle.dumps,而不是pickle.dump(第二个参数接受类似文件的对象)

    >>> import cPickle as pickle
    >>> pickle.dump('not a real image data', -1)
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    TypeError: argument must have 'write' attribute
    >>> pickle.dumps('not a real image data', -1)
    '\x80\x02U\x15not a real image dataq\x01.'
    

    client_socket.send(pickle.dumps(img_data, -1))
                                  ^
    

    【讨论】:

    • @CoarguAliquis,是的,除非您想从类似文件的对象中加载它。 pickle.loads 接受腌制字符串。
    • 我现在试了一下,得到了EOFError,没有任何关于问题的解释。
    • @CoarguAliquis,如果你能告诉我完整的回溯,那就太好了。
    • 回溯是 Traceback (most recent call last): File "C:/py-prog/client.py", line 21, in &lt;module&gt; actions_funcs.show_img(data) File "C:/py-prog\actions_funcs.py", line 41, in show_img img = pickle.loads(data) EOFError 。我检查了腌制数据的 len,它大于 1024。有没有办法预测腌制输出的大小?
    • @CoarguAliquis,错误的原因是您没有提供完整的腌制字符串。 IOW,你没有收到完整的腌制字符串。
    猜你喜欢
    • 1970-01-01
    • 2022-07-05
    • 1970-01-01
    • 1970-01-01
    • 2016-05-30
    • 1970-01-01
    • 1970-01-01
    • 2017-01-12
    • 2021-12-13
    相关资源
    最近更新 更多