python里仅收集所有协程执行结果

来源:互联网 发布:内容运营优化 编辑:程序博客网 时间:2024/05/22 15:00

跟老菜鸟学python
http://edu.csdn.net/course/detail/2592

Python游戏开发入门

http://edu.csdn.net/course/detail/5690

有这么样的一种需求,比如使用多协程来计算加密结果,像这样没有取消任务的需求,也不会出现异常的,可以使用gather()函数来并发运行协程更方便:

import asyncioasync def phase1():    print('in phase1')    await asyncio.sleep(2)    print('done with phase1')    return 'phase1 result'async def phase2():    print('in phase2')    await asyncio.sleep(1)    print('done with phase2')    return 'phase2 result'async def main():    print('starting main')    print('waiting for phases to complete')    results = await asyncio.gather(        phase1(),        phase2(),    )    print('results: {!r}'.format(results))event_loop = asyncio.get_event_loop()try:    event_loop.run_until_complete(main())finally:    event_loop.close()

结果输出如下:

starting main
waiting for phases to complete
in phase2
in phase1
done with phase2
done with phase1
results: ['phase1 result', 'phase2 result']