作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我想序列化一个具有套接字对象作为值的字典,但我无法让事情正常工作。
这是我的代码:
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)
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/
我是一名优秀的程序员,十分优秀!