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


前言

本文主要给大家介绍了关于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'

总结

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

评论关闭