遍历将来的结果时,如何获取发送给ThreadPoolExecutor的参数?

问题描述

我使用ThreadPoolExecutor快速检查代理列表,以查看哪些代理已死或还活着。

with concurrent.futures.ThreadPoolExecutor(max_workers=5) as executor:
    futures = []
    for proxy in proxies:
        future = executor.submit(is_proxy_alive,proxy)
        futures.append(future)
    
    for future in futures:
        print(future.result()) # prints true or false depending on if proxy is alive.
                               # how do I get the specific proxy I passed in the arguments 
                               # so that I can make a dictionary here?

我的目标是让我在遍历结果时传递给执行程序的参数(代理),以了解哪些确切的代理是死的还是活的,因此我可以制作一个看起来像这样的字典:

{"IP1": False,"IP2": True,"IP3": True}

我能想到的一种方法是返回我发送的代理,然后返回真/假,但是有更好的外部方法可以使函数不必仅仅返回布尔值吗?

解决方法

提交任务时,您可以创建从Future到其代理的映射。

with concurrent.futures.ThreadPoolExecutor(max_workers=5) as executor:
    future_proxy_mapping = {} 
    futures = []
    for proxy in proxies:
        future = executor.submit(is_proxy_alive,proxy)
        future_proxy_mapping[future] = proxy
        futures.append(future)
    
    for future in futures:
        proxy = future_proxy_mapping[future]
        print(proxy)
        print(future.result())

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...