在迭代未来结果时,如何获取发送给 ThreadPoolExecutor 的参数?

nat*_*han 7 python concurrency multithreading python-3.x concurrent.futures

我使用 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?
Run Code Online (Sandbox Code Playgroud)

我的目标是在迭代结果时获取传递给执行器的参数(代理),以了解哪些确切的代理已死或活,因此我可以制作一个可能如下所示的字典:

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

我能想到的一种方法是在返回 true/false 的基础上返回我发送的代理,但是有没有更好的方法可以在外部执行此操作,以便该函数不必返回超过 bool 的值?

Anm*_*ggi 17

提交任务时,您可以创建从 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())
Run Code Online (Sandbox Code Playgroud)

  • 谢谢,如果 futures 对象能够首先存储这个映射,这样我们就可以调用它 (2认同)