【问题标题】:Multiprocessing, dynamic nested manager not working in windows (fine on Macs)多处理、动态嵌套管理器在 Windows 中不起作用(在 Mac 上很好)
【发布时间】:2021-03-06 11:24:30
【问题描述】:

这是在线程中运行线程的一个大大简化的版本,我分别调用各种 api 组。有时这些组将按顺序运行,有时同时运行。以下是在 mac 上运行良好的简化代码:

from multiprocessing import Process, Manager

def test(index):
    my_dict[index] = manager.dict()
    my_dict[index]['status'] = 200

def collate_tests():
    apis = []
    for i in range(10):
        apis.append(Process(target=test, args=(f"{i}",)))

for index, value in enumerate(apis):
    print (f"Execute {index +1} of {len(apis)} Tests")
    value.start()

for api in apis:
    api.join()


if __name__ == '__main__':
    manager = Manager()
    my_dict = manager.dict()
    run_test = Process(target=collate_tests)

    run_test.start()
    run_test.join()

    for k,v in my_dict.items():
        print (k,v)

我得到结果

0 {'status': 200}
1 {'status': 200}
2 {'status': 200}
4 {'status': 200}
3 {'status': 200}
5 {'status': 200}
6 {'status': 200}
7 {'status': 200}
9 {'status': 200}
8 {'status': 200}

在windows中我得到

NameError: name ‘my_dict’ is not defined

所以我将 my_dict 作为 args 传递,然后我得到:

NameError: name ‘manager’ is not defined

如果我将 manager 作为参数传递

TypeError : can’t pickle weakref objects

所以我似乎无法设置这条线

my_dict = manager.dict()

我什至尝试在 test() 方法中实例化另一个管理器。但这也让我无处可去,因为我无法迭代创建的 dict 代理。有什么建议吗?

注意设置嵌套管理器的标准方法

if __name__ == '__main__':

不可行,因为我不知道'index' my_dict[index] 会提前是什么。我正在尝试的东西在 Windows 中是否可行?

PS - 我已经搜索了网络,但没有找到我正在寻找的解决方案。谢谢

【问题讨论】:

    标签: python-3.x windows dynamic nested multiprocessing


    【解决方案1】:

    执行嵌套字典并将其分配给键就可以了。

    def test(index, my_dict):
    
       nest = {}
    
       nest['status'] = 200
    
       my_dict[index] = nest
    

    【讨论】:

      猜你喜欢
      • 2018-02-26
      • 2020-12-03
      • 1970-01-01
      • 2017-04-05
      • 2022-01-22
      • 1970-01-01
      • 1970-01-01
      • 2014-07-29
      • 2016-08-17
      相关资源
      最近更新 更多