遍历将来的结果时,如何获取发送给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())