【发布时间】:2021-06-24 22:17:18
【问题描述】:
下面是一个收集 URL 长度的简单程序。
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 中忽略了异常?如何解决?
Traceback 是:RuntimeError: Event loop is closed 特别是 Exception ignored in: <function _ProactorBasePipeTransport.__del__ at 0x000001F8A7A713A0>
【问题讨论】:
-
是运行时错误吗?或者这是一个警告?它可能希望你对
asyncio.wait返回的任务做点什么。 -
请更新问题以包含回溯。
-
看起来您使用的是 Windows,在这种情况下,这是 aiohttp 中的一个已知问题 github.com/aio-libs/aiohttp/issues/4324
标签: python-3.x python-asyncio aiohttp