从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))
False
False
False
<class 'coroutine'>
<class 'str'>
False
False
False
<class 'coroutine'>
<class 'str'>
False
False
False
<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'
)
相关分类