如何在发生错误时重新执行 ThreadPoolExecutor 中的函数?

How to re-execute function in ThreadPoolExecutor in case of error?

我正在尝试 python 的 concurrent.futures 文档中的这个 example code for python's ThreadPoolExecutor。具体

import concurrent.futures
import urllib.request

URLS = ['http://www.foxnews.com/',
        'http://www.cnn.com/',
        'http://europe.wsj.com/',
        'http://www.bbc.co.uk/',
        'http://some-made-up-domain.com/']

# Retrieve a single page and report the URL and contents
def load_url(url, timeout):
    with urllib.request.urlopen(url, timeout=timeout) as conn:
        return conn.read()

# We can use a with statement to ensure threads are cleaned up promptly
with concurrent.futures.ThreadPoolExecutor(max_workers=5) as executor:
    # Start the load operations and mark each future with its URL
    future_to_url = {executor.submit(load_url, url, 60): url for url in URLS}
    for future in concurrent.futures.as_completed(future_to_url):
        url = future_to_url[future]
        try:
            data = future.result()
        except Exception as exc:
            print('%r generated an exception: %s' % (url, exc))
        else:
            print('%r page is %d bytes' % (url, len(data)))

如果concurrent.futures.as_completed(future_to_url)循环中出现异常,如何重新调用执行器?基本上我只是想重试失败的工作。

我试过简单地调用 executor.submit(...) 之类的东西,但它似乎不起作用。

欢迎任何建议,谢谢

期货失败后兑现。失败是他们的价值。因此,你不能重新执行它们,你必须创建一个新的 Future。

因为您有 URL,您可以在错误处理程序上执行此操作,并在 future_to_url 中的 Futures 完成后,迭代添加到不同集合的新 Futures。