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设计】的支持。

相关文章

pyshp创建shp点文件的方法

如下所示: # coding:utf-8 import shapefile w = shapefile.Writer() w.autoBalance = 1 w = shapef...

新手如何发布Python项目开源包过程详解

新手如何发布Python项目开源包过程详解

本文假设你在 GitHub 上已经有一个想要打包和发布的项目。 第 0 步:获取项目许可证 在做其他事之前,由于你的项目要开源,因此应该有一个许可证。获取哪种许可证取决于项目包的使用方式...

Python小游戏之300行代码实现俄罗斯方块

Python小游戏之300行代码实现俄罗斯方块

前言 本文代码基于 python3.6 和 pygame1.9.4。 俄罗斯方块是儿时最经典的游戏之一,刚开始接触 pygame 的时候就想写一个俄罗斯方块。但是想到旋转,停靠,消除等操...

python中cPickle类使用方法详解

在python中,一般可以使用pickle类来进行python对象的序列化,而cPickle提供了一个更快速简单的接口,如python文档所说的:“cPickle – A faster...

django中forms组件的使用与注意

forms组件 django框架提供了一个Form类,来进行web开发中的表单提交数据的处理工作。 导入相关模块 from django import forms from dja...