【发布时间】:2019-08-10 11:37:27
【问题描述】:
我已经阅读并再次阅读了有关多处理模块和队列管理的 Python 文档,但我找不到与此问题相关的任何内容,这让我发疯并阻止了我的项目:
我编写了一个“JsonLike”类,它允许我创建一个对象,例如:
a = JsonLike()
a.john.doe.is.here = True
...不考虑中间初始化(非常有用)
以下代码只是创建了这样一个对象,将其设置并插入到数组中并尝试将其发送到进程(这是我需要的,但是发送对象本身会导致相同的错误强>)
考虑到这段代码:
from multiprocessing import Process, Queue, Event
class JsonLike(dict):
"""
This class allows json-crossing-through creation and setting such as :
a = JsonLike()
a.john.doe.is.here = True
it automatically creates all the hierarchy
"""
def __init__(self, *args, **kwargs):
# super(JsonLike, self).__init__(*args, **kwargs)
dict.__init__(self, *args, **kwargs)
for arg in args:
if isinstance(arg, dict):
for k, v in arg.items():
self[k] = v
if kwargs:
for k, v in kwargs.items():
self[k] = v
def __getattr__(self, attr):
if self.get(attr) != None:
return attr
else:
newj = JsonLike()
self.__setattr__(attr, newj)
return newj
def __setattr__(self, key, value):
self.__setitem__(key, value)
def __setitem__(self, key, value):
dict.__setitem__(self, key, value)
self.__dict__.update({key: value})
def __delattr__(self, item):
self.__delitem__(item)
def __delitem__(self, key):
dict.__delitem__(self, key)
del self.__dict__[key]
def readq(q, e):
while True:
obj = q.get()
print('got')
if e.is_set():
break
if __name__ == '__main__':
q = Queue()
e = Event()
obj = JsonLike()
obj.toto = 1
arr=[obj]
proc = Process(target=readq, args=(q,e))
proc.start()
print(f"Before sending value :{arr}")
q.put(arr)
print('sending done')
e.set()
proc.join()
proc.close()
我得到以下输出(在q.put):
Before sending value :[{'toto': 1}]
Traceback (most recent call last):
sending done
File "/usr/lib/python3.7/multiprocessing/queues.py", line 236, in _feed
obj = _ForkingPickler.dumps(obj)
File "/usr/lib/python3.7/multiprocessing/reduction.py", line 51, in dumps
cls(buf, protocol).dump(obj)
TypeError: 'JsonLike' object is not callable
有什么建议吗?
【问题讨论】:
-
呃,不是很相关,而且更像是我的一个小便,但这不是“Json-like”,它是 dict like。 JSON 是一种基于文本的序列化格式。当你反序列化它时,它不再是 JSON。现在是一些物化的数据结构
-
好吧,让我们说类似javascript的json getter/setter,但正如你所说,与暴露的问题无关。
标签: python pickle python-multiprocessing python-3.7