如何获取 return 异步协程的值 python
how to get return value of async coroutine python
我是 python 的新手,正在尝试学习 asyncio 模块。我对从异步任务中获取 return 值感到沮丧。有一个 post 谈到了这个话题,但它无法判断哪个值是由哪个任务 returned 的(假设某个网页响应速度比另一个更快)。
下面的代码试图同时获取三个网页,而不是一个一个地获取。
import asyncio
import aiohttp
async def fetch(url):
async with aiohttp.ClientSession() as session:
async with session.get(url) as resp:
assert resp.status == 200
return await resp.text()
def compile_all(urls):
tasks = []
for url in urls:
tasks.append(asyncio.ensure_future(fetch(url)))
return tasks
urls = ['https://python.org', 'https://google.com', 'https://amazon.com']
tasks = compile_all(urls)
loop = asyncio.get_event_loop()
a, b, c = loop.run_until_complete(asyncio.gather(*tasks))
loop.close()
print(a)
print(b)
print(c)
首先,尽管它确实打印了一些 html 文档,但它遇到了运行时错误:运行时错误:事件循环已关闭。
其次,问题是:这样真的保证a,b,c会按照urls[0],url的顺序对应到urls列表吗[1], urls[2] 网页? (我假设异步任务执行不能保证这一点)。
第三,有没有其他更好的方法或者在这种情况下我应该使用队列吗?如果是,怎么做?
任何帮助将不胜感激。
结果的顺序将与网址的顺序相对应。查看 asyncio.gather:
的文档
If all awaitables are completed successfully, the result is an
aggregate list of returned values. The order of result values
corresponds to the order of awaitables in aws.
要在任务完成时处理任务,您可以使用 asyncio.as_completed. This 有更多关于如何使用它的信息。
我是 python 的新手,正在尝试学习 asyncio 模块。我对从异步任务中获取 return 值感到沮丧。有一个 post
下面的代码试图同时获取三个网页,而不是一个一个地获取。
import asyncio
import aiohttp
async def fetch(url):
async with aiohttp.ClientSession() as session:
async with session.get(url) as resp:
assert resp.status == 200
return await resp.text()
def compile_all(urls):
tasks = []
for url in urls:
tasks.append(asyncio.ensure_future(fetch(url)))
return tasks
urls = ['https://python.org', 'https://google.com', 'https://amazon.com']
tasks = compile_all(urls)
loop = asyncio.get_event_loop()
a, b, c = loop.run_until_complete(asyncio.gather(*tasks))
loop.close()
print(a)
print(b)
print(c)
首先,尽管它确实打印了一些 html 文档,但它遇到了运行时错误:运行时错误:事件循环已关闭。
其次,问题是:这样真的保证a,b,c会按照urls[0],url的顺序对应到urls列表吗[1], urls[2] 网页? (我假设异步任务执行不能保证这一点)。
第三,有没有其他更好的方法或者在这种情况下我应该使用队列吗?如果是,怎么做?
任何帮助将不胜感激。
结果的顺序将与网址的顺序相对应。查看 asyncio.gather:
的文档If all awaitables are completed successfully, the result is an aggregate list of returned values. The order of result values corresponds to the order of awaitables in aws.
要在任务完成时处理任务,您可以使用 asyncio.as_completed. This