遍历将来的结果时,如何获取发送给ThreadPoolExecutor的参数? [英] How can I get the arguments I sent to ThreadPoolExecutor when iterating through future results?
问题描述
我使用ThreadPoolExecutor快速检查代理列表,以查看哪些代理已死或还活着.
I use a ThreadPoolExecutor to quickly check a list of proxies to see which ones are dead or alive.
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?
我的目标是获取在迭代结果时传递给执行程序的参数(代理),以了解哪些确切的代理已经死或还活着,因此我可以制作一个看起来像这样的字典:
My goal is to get the argument (the proxy) I passed to the executor when iterating through the results to know which exact proxies are dead or alive, so I could make a dictionary that might look like this:
{"IP1":False,"IP2":True,"IP3":True}
我能想到的一种方法是在返回true/false的基础上返回我发送的代理,但是是否有更好的方法可以在外部执行此操作,因此该函数不必只返回布尔值?>
One method I can think of is returning the proxy I sent on top of returning true/false, but is there a better way to do it externally so the function doesn't have to return more than just a bool?
推荐答案
在提交任务时,您可以创建从future到其代理的映射.
While submitting the task, you could create a mapping from future to its proxy.
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())
这篇关于遍历将来的结果时,如何获取发送给ThreadPoolExecutor的参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!