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 读取线的shp文件实例详解

如下所示: import shapefile sf = shapefile.Reader("E:\\1.2\\cs\\DX_CSL.shp") shapes = sf.shapes(...

python中urllib.unquote乱码的原因与解决方法

发现问题 Python中的urllib模块用来处理url相关的操作,unquote方法对应javascript中的urldecode方法,它对url进行解码,把类似"%xx"的字符替换成...

对python使用http、https代理的实例讲解

在国内利用Python从Internet上爬取数据时,有些网站或API接口被限速或屏蔽,这时使用代理可以加速爬取过程,减少请求失败,Python程序使用代理的方法主要有以下几种: (1)...

python实现上传下载文件功能

最近刚学python,遇到上传下载文件功能需求,记录下! django web项目,前端上传控件用的是uploadify。 文件上传 - 后台view 的 Python代码如下: @...

python使用tkinter实现简单计算器

本文实例为大家分享了python使用tkinter实现简单计算器的具体代码,供大家参考,具体内容如下 class Counter: #引入tkinter import tki...