代码之家  ›  专栏  ›  技术社区  ›  crash

如果出现错误,如何在ThreadPoolExecutor中重新执行函数?

  •  0
  • crash  · 技术社区  · 7 年前

    我在试这个 example code for python's ThreadPoolExecutor 来自python的 concurrent.futures 文档。明确地

    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(...) 但似乎没用。

    欢迎提出任何建议,谢谢

    0 回复  |  直到 7 年前
        1
  •  1
  •   Javier    7 年前

    未来在失败后实现。失败是他们的价值所在。因此,你不能重新执行它们,你必须创造一个新的未来。

    既然有了URL,就可以在错误处理程序上执行它,在 future_to_url 完成,迭代添加到不同集合的新未来。