我正在学习如何使用 concurrent withexecutor.map()和executor.submit()。
我有一个包含 20 个 url 的列表,想同时发送 20 个请求,问题是.submit()从一开始就以与给定列表不同的顺序返回结果。我读过它map()可以满足我的需要,但我不知道如何用它编写代码。
下面的代码对我来说很完美。
问题:是否有任何代码块map()等同于下面的代码,或者任何排序方法可以submit()按给定列表的顺序对结果列表进行排序?
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)))
一只萌萌小番薯
幕布斯6054654
相关分类