futures.ThreadPoolExecutor例外

时间:2017-07-28 21:26:22

标签: python multithreading python-multithreading

我实施futures.ThreadPoolExecutor并希望将广泛Exception更改为特定例外(例如ValueError)。使用下面的示例,我应该添加load_url而不是广泛的Exception生成的例外吗?这部分代码所指的例外情况。

使用this页面作为参考:

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):
    if not url:
       raise ValueError('Invalid URL')
    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)))

0 个答案:

没有答案