我有这段代码,当有异常时,未设置事件。如果我将超时时间增加到10,则事件已设置。
为什么事件不在异常期间?
import sys
print(sys.version)
from concurrent import futures
import urllib.request
import multiprocessing
import time
URLS = ['http://www.foxnews.com/',
'http://www.cnn.com/',
'http://europe.wsj.com/',
'http://www.bbc.co.uk/',
'http://some-made-up-domain.com/']
def load_url(url, e, timeout=0):
print('load_url')
time.sleep(1)
try:
result = urllib.request.urlopen(url, timeout=timeout).read()
except Exception as e:
print(e)
e.set()
return result
def main():
manager = multiprocessing.Manager()
e = manager.Event()
with futures.ThreadPoolExecutor(max_workers=5) as executor:
future_to_url = dict(
(executor.submit(load_url, url, e), url)
for url in URLS)
print('waiting to set the event')
e.wait()
print('event set')
for future in futures.as_completed(future_to_url):
url = future_to_url[future]
try:
print('%r page is %d bytes' % (
url, len(future.result())))
except Exception as e:
print('%r generated an exception: %s' % (
url, e))
if __name__ == '__main__':
main()
答案 0 :(得分:0)
很好...原因实际上很简单。您的except Exception as e:
会覆盖该e
变量。