这是我的代码。
from multiprocessing.managers import BaseManager
from threading import Thread
def manager1():
my_dict = {}
my_dict['key'] = "value"
print(my_dict['key']) #this works
class SyncManager(BaseManager): pass
SyncManager.register('get_my_dict', callable=lambda:my_dict)
n = SyncManager(address=('localhost', 50001), authkey=b'secret')
t = n.get_server()
t.serve_forever()
def get_my_dict_from_the_manager():
class SyncManager(BaseManager): pass
SyncManager.register('get_my_dict')
n = SyncManager(address=('localhost', 50001), authkey=b'secret')
n.connect()
my_dict = n.get_my_dict()
return my_dict
thread1 = Thread(target=manager1)
thread1.daemon = True
thread1.start()
my_dict = get_my_dict_from_the_manager()
print(my_dict.keys()) #this works
print(my_dict['key']) #DOES NOT WORK
在脚本的最后一行,我尝试通过用键下标来访问字典my_dict
中的值。这将引发错误。这是我的终端输出:
value
['key']
Traceback (most recent call last):
File "/home/magnus/PycharmProjects/docker-falcon/app/so_test.py", line 31, in <module>
print(my_dict['key'])
TypeError: 'AutoProxy[get_my_dict]' object is not subscriptable
Process finished with exit code 1
似乎AutoProxy
对象的行为类似于应该代理的dict
,但不完全相同。有没有办法使它可以下标?
答案 0 :(得分:1)
问题在于AutoProxy
对象没有公开__getitem__
通常具有的dict
方法。通过对我的similar question的回答,您可以按其键访问项目:只需将print(my_dict['key'])
替换为print(my_dict.get('key'))