python中利用await关键字如何等待Future对象完成详解

(编辑:jimmy 日期: 2024/9/26 浏览:2)

前言

本文主要给大家介绍了关于python用await关键字等待Future对象完成的相关内容,分享出来供大家参考学习,下面话不多说了,来一起看看详细的介绍吧。

在下面的例子里,演示了怎么样使用await来等Future对象设置结果完成

示例代码如下:

import asyncio 
 
 
def mark_done(future, result): 
 print('setting future result to {!r}'.format(result)) 
 future.set_result(result) 
 
 
async def main(loop): 
 all_done = asyncio.Future() 
 
 print('scheduling mark_done') 
 loop.call_soon(mark_done, all_done, 'the result') 
 
 result = await all_done 
 print('returned result: {!r}'.format(result)) 
 
 
event_loop = asyncio.get_event_loop() 
try: 
 event_loop.run_until_complete(main(event_loop)) 
finally: 
 event_loop.close() 

输出结果如下:

scheduling mark_done
setting future result to 'the result'
returned result: 'the result'

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作能带来一定的帮助,如果有疑问大家可以留言交流,谢谢大家对的支持。

一句话新闻

高通与谷歌联手!首款骁龙PC优化Chrome浏览器发布
高通和谷歌日前宣布,推出首次面向搭载骁龙的Windows PC的优化版Chrome浏览器。
在对骁龙X Elite参考设计的初步测试中,全新的Chrome浏览器在Speedometer 2.1基准测试中实现了显著的性能提升。
预计在2024年年中之前,搭载骁龙X Elite计算平台的PC将面世。该浏览器的提前问世,有助于骁龙PC问世就获得满血表现。
谷歌高级副总裁Hiroshi Lockheimer表示,此次与高通的合作将有助于确保Chrome用户在当前ARM兼容的PC上获得最佳的浏览体验。