python中利用Future对象异步返回结果示例代码

yipeiwu_com6年前Python基础

前言

本文主要给大家介绍了关于python中用Future对象异步返回结果的相关内容,分享出来供大家参考学习,下面话不多说了,来一起看看详细的介绍吧。

一个Future是用来表示将来要完成的结果,异步循环可以自动完成对这种对象的状态触发。

例子如下:

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

输出结果如下:

scheduling mark_done
entering event loop
setting future result to 'the result'
returned result: 'the result'
closing event loop
future result: 'the result'

在这个例子里,并没有调用return语句,但也可以生成一个结果返回。Future的使用跟协程使用是一样的。

总结

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

相关文章

Python PIL图片添加字体的例子

Python PIL图片添加字体的例子

效果 左边原图,右面添加字体后保存的图。 代码 # -*- coding: utf-8 -*- import PIL.Image as Image import PIL.Image...

Python 实现中值滤波、均值滤波的方法

Python 实现中值滤波、均值滤波的方法

红包: Lena椒盐噪声图片: # -*- coding: utf-8 -*- """ Created on Sat Oct 14 22:16:47 2017 @author:...

在Python中通过getattr获取对象引用的方法

getattr函数 (1)使用 getattr 函数,可以得到一个直到运行时才知道名称的函数的引用。 >>> li = ["Larry", "Curly"] >...

python脚本监控docker容器

本文实例为大家分享了python脚本监控docker容器的方法,供大家参考,具体内容如下 脚本功能: 1、监控CPU使用率 2、监控内存使用状况 3、监控网络流量 具体代码: #!/...

对python3 Serial 串口助手的接收读取数据方法详解

其实网上已经有许多python语言书写的串口,但大部分都是python2写的,没有找到一个合适的python编写的串口助手,只能自己来写一个串口助手,由于我只需要串口能够接收读取数据就可...