为了账号安全,请及时绑定邮箱和手机立即绑定

asyncio.as_completed 是否产生期货或协程?

asyncio.as_completed 是否产生期货或协程?

当年话下 2021-08-05 15:02:41
从asyncio 文档:asyncio.as_completed(aws, *, loop=None, timeout=None)同时运行 aws 集中的可等待对象。返回 Future 对象的迭代器。返回的每个 Future 对象都代表剩余的可等待对象集的最早结果。我会承担这些的Future对象在描述的方法asyncio.Future:.cancelled(),.exception(),和.result()。但似乎产生的元素只是协程,而不是Future对象。我错过了什么?这似乎违背了 的描述.as_completed()。如果需要,协程如何“完成” await?>>> import asyncio>>> import aiohttp>>> >>> async def get(session, url):...     async with session.request('GET', url) as resp:...         t = await resp.text()...         return t... >>> async def bulk_as_completed(urls):...     async with aiohttp.ClientSession() as session:...         aws = [get(session, url) for url in urls]...         for future in asyncio.as_completed(aws):...             for i in ('cancelled', 'exception', 'result'):...                 print(hasattr(future, i))...             print(type(future))...             try:...                 result = await future...             except:...                 pass...             else:...                 print(type(result))...                 print()... >>> >>> urls = (...     'https://docs.python.org/3/library/asyncio-task.html',...     'https://docs.python.org/3/library/select.html',...     'https://docs.python.org/3/library/this-page-will-404.html',... )>>> >>> asyncio.run(bulk_as_completed(urls))FalseFalseFalse<class 'coroutine'><class 'str'>FalseFalseFalse<class 'coroutine'><class 'str'>FalseFalseFalse<class 'coroutine'><class 'str'>归根结底,我关心这个的原因是因为我想让异常像在asyncio.gather(..., return_exceptions=True). 考虑添加一个在session.request()被调用时会引发的虚假 URL :urls = (    'https://docs.python.org/3/library/asyncio-task.html',    'https://docs.python.org/3/library/select.html',    'https://docs.python.org/3/library/this-page-will-404.html',    # This URL will raise on session.request().  How can I propagate    # that exception to the iterator of results?    'https://asdfasdfasdf-does-not-exist-asdfasdfasdf.com')
查看完整描述

1 回答

  • 1 回答
  • 0 关注
  • 153 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信