gpt4 book ai didi

python-3.x - 如何在python中使用pickle序列化套接字对象

转载 作者:行者123 更新时间:2023-12-03 22:55:11 25 4
gpt4 key购买 nike

我想序列化一个具有套接字对象作为值的字典,但我无法让事情正常工作。

这是我的代码:

self.client_dictionary[username] = socket.socket() # update dictionary
file = open('client_sockets.pickle','wb')
pickle.dump(self.client_dictionary, file) #here is where the error is
file.close()

但我收到以下错误:
File "D:\Users\saunfe\AppData\Local\Programs\Python\Python35- 
32\lib\socket.py",
line 175, in __getstate__ raise TypeError("Cannot serialize socket object")

TypeError: Cannot serialize socket object

最佳答案

套接字对象不能被腌制。 pickle module 的文档解释了哪些类型可以被腌制:

The following types can be pickled:

  • None, True, and False

  • integers, floating point numbers, complex numbers

  • strings, bytes, bytearrays

  • tuples, lists, sets, and dictionaries containing only picklable objects

  • functions defined at the top level of a module (using def, not lambda)

  • built-in functions defined at the top level of a module

  • classes that are defined at the top level of a module

  • instances of such classes whose __dict__ or the result of calling __getstate__() is picklable (see section Pickling Class Instances for details).



现在是 socket object 不是这些类型中的任何一种,它甚至没有 __dict__ (和它的 __getstate__() 提示它不能被腌制)。

从您编写问题的方式来看,您最有可能想要腌制套接字的客户端连接,而不是套接字本身。由于您有一个空套接字(通过查看代码片段),您应该将参数腌制到套接字构造函数中,如下所示:
from socket import socket
import pickle

socket_args = {}
self.client_dictionary[username] = socket_args # update dictionary
file = open('client_sockets.pickle','wb')
pickle.dump(self.client_dictionary, file)
file.close()
# ...

# file open and load omitted for brevity
socket_args = self.client_dictionary[username]
socket_object = socket(**socket_args)

如果套接字调用有参数,比如`socket(family=socket.AF_INET, type=socket.SOCK_STREAM, proto=0),你可以使用这个字典:
import socket
socket_args = {'family': socket.AF_INET, 'type': socket.SOCK_STREAM, 'proto': 0}
# ...

# pickle socket_args here
# ...

# load socket_args
socket_object = socket.socket(**socket_args)

关于python-3.x - 如何在python中使用pickle序列化套接字对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54279466/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com