代码之家  ›  专栏  ›  技术社区  ›  Alexander Obidiegwu

多处理代码在while循环中不起作用

  •  2
  • Alexander Obidiegwu  · 技术社区  · 2 年前

    星期天快乐。

    我有这段代码,我想使用多处理模块来运行它。但这不仅仅是出于某种原因。

    with ProcessPoolExecutor() as executor:
        while True:
            if LOCAL_RUN:
                print("ALERT: Doing a local run of the automation with limited capabilities.")
    
            list_of_clients = db_manager.get_clients()
            random.shuffle(list_of_clients)
    
            list_of_not_attempted_clients_domains = db_manager.tags()
            group_of_clients_handlers = {}
    
            # no matches
            if not list_of_not_attempted_clients_domains:
                sleep = 60 * 10
                pretty_print(f'No matches found. Sleeping for {sleep}s')
                time.sleep(sleep)
                continue
    
            for client in list_of_clients:
                client_id = client[0]
                client_name = client[1]
                group_of_clients_handlers[client_id] = [ClientsHandler(db_manager), client_name]
    
            #  MULTI-PROCESSING CODE
            try:
                print('running function...')
                executor.map(
                    partial(run, group_of_clients_handlers=group_of_clients_handlers),
                    list_of_not_attempted_clients_domains
                )
            except Exception as err:
                print(err)
    

    尽管我一直在尝试调试它,但我不知道为什么它不起作用,尽管我觉得它与启动或安排任务等需要时间的过程有关,但我不能确定。

    while循环一直在运行,我看到所有的打印语句 running function... 但是run函数从不执行。run函数是一个非常大的函数,具有嵌套的大函数。

    except块也不会打印出任何错误。很想听听你的想法。。。

    1 回复  |  直到 2 年前
        1
  •  2
  •   Ahmed AEK    2 年前

    ProcessPoolExecutor.map 创建迭代器时,必须使用迭代器才能获取异常,否则将丢弃该异常。

    from concurrent.futures import ProcessPoolExecutor
    
    def raising_func(val):
      raise ValueError(val)
    
    with ProcessPoolExecutor(4) as pool:
      pool.map(raising_func, [1,2,3,4,5])
    
    with ProcessPoolExecutor(4) as pool:
      list(pool.map(raising_func, [1,2,3,4,5]))  # < ---- exception is thrown from here