如何获取通过 asyncio task 方式运行的函数的返回值:
- asyncio.wait
- asyncio.gather
- future.result
asyncio.wait 与 asyncio.gather 对比:
asyncio.wait 比 asynci.gather 更低级,asyncio.gather 主要集中在收集结果,它等待并按给定的顺序返回其结果,asyncio.wait 只是等待,它不是直接给出结果,而是给出已完成和挂起的任务。
asyncio.gather 允许对任务进行高级别分组;asyncio.wait 支持在完成第一个任务后或在指定的超时之后等待停止,从而允许操作的精度降低。
async.gather
#!/usr/bin/env python3
import asyncio
async def func_normal():
print('A')
await asyncio.sleep(5)
print('B')
return 'saad'
async def func_infinite():
for i in range(10):
print("--%d" % i)
return 'saad2'
loop = asyncio.get_event_loop()
tasks = [func_normal(), func_infinite()]
results = loop.run_until_complete(asyncio.gather(*tasks))
print("func_normal()={}, func_infinite()={}".format(*results))
loop.close()
async.wait
import asyncio
async def func_normal():
print("A")
await asyncio.sleep(5)
print("B")
return 'saad'
async def func_infinite():
i = 0
while i<10:
print("--"+str(i))
i = i+1
return('saad2')
loop = asyncio.get_event_loop()
tasks = [ func_normal(), func_infinite()]
done, _ = loop.run_until_complete(asyncio.wait(tasks))
for fut in done:
print("return value is {}".format(fut.result()))
loop.close()
也可以通过
print(tasks[0].result())
print(tasks[1].result())
获取对应的结果
future.result
import asyncio
async def func_normal(future):
print("A")
await asyncio.sleep(5)
print("B")
# return 'saad'
future.set_result('saad')
async def func_infinite(future):
i = 0
while i<10:
print("--"+str(i))
i = i+1
# return('saad2')
future.set_result('saad2')
def got_result(future):
print(future.result())
loop = asyncio.get_event_loop()
future1 = asyncio.Future()
future2 = asyncio.Future()
future1.add_done_callback(got_result)
future2.add_done_callback(got_result)
# Coros are automatically wrapped in Tasks by asyncio.wait()
coros = [
func_normal(future1),
func_infinite(future2)]
loop.run_until_complete(asyncio.wait(coros))
loop.close()