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

yipeiwu_com5年前Python基础

前言

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

总结

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

相关文章

python对象销毁实例(垃圾回收)

我就废话不多说了,直接上代码吧! '''python对象销毁(垃圾回收)''' class Point: 'info class' def __init__(self,x...

Python Collatz序列实现过程解析

编写一个名为 collatz()的函数,它有一个名为 number 的参数。如果参数是偶数,那么 collatz()就打印出 number // 2, 并返回该值。如果 number 是...

Linux中Python 环境软件包安装步骤

简介: 记录一下关于 Python 环境软件包的一些安装步骤 1、升级 Python 到 2.7.10( 默认 2.6.6 ) shell > yum -y install e...

python正则表达式去掉数字中的逗号(python正则匹配逗号)

分析 数字中经常是3个数字一组,之后跟一个逗号,因此规律为:***,***,*** 正则式复制代码 代码如下:[a-z]+,[a-z]? 复制代码 代码如下:import re sen...

python字典键值对的添加和遍历方法

添加键值对 首先定义一个空字典 >>> dic={} 直接对字典中不存在的key进行赋值来添加 >>> dic['name']='zhangsan...