下面是一个简单的程序,用于收集URL长度。
为什么以下代码在Python 3.9中会因为运行时错误并忽略异常而失败?如何修复?
回溯信息是:
import aiohttp
import asyncio
from time import perf_counter
URLS = ['http://www.cnn.com', 'http://www.huffpost.com', 'http://europe.wsj.com',
'http://www.bbc.co.uk', 'http://failfailfail.com']
async def async_load_url(url, session):
try:
async with session.get(url) as resp:
content = await resp.read()
print(f"{url!r} is {len(content)} bytes")
except IOError:
print(f"failed to load {url}")
async def main():
async with aiohttp.ClientSession() as session:
tasks = [async_load_url(url, session) for url in URLS]
await asyncio.wait(tasks)
if __name__ == "__main__":
start = perf_counter()
asyncio.run(main())
elapsed = perf_counter() - start
print(f"\nTook {elapsed} seconds")
为什么以下代码在Python 3.9中会因为运行时错误并忽略异常而失败?如何修复?
回溯信息是:
RuntimeError: Event loop is closed
,具体来说是与Exception ignored in: <function _ProactorBasePipeTransport.__del__ at 0x000001F8A7A713A0>
相关。
asyncio.wait
返回的任务执行某些操作。 - dirn