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

相关文章

Linux下python3.7.0安装教程

Linux下python3.7.0安装教程

记录了Linux 安装python3.7.0的详细过程,供大家参考,具体内容如下 我这里使用的时centos7-mini,centos系统本身默认安装有python2.x,版本x根据不同...

python用模块zlib压缩与解压字符串和文件的方法

python中zlib模块是用来压缩或者解压缩数据,以便保存和传输。它是其他压缩工具的基础。下面来一起看看python用模块zlib压缩与解压字符串和文件的方法。话不多说,直接来看示例代...

python中正则表达式 re.findall 用法

Python 正则表达式 正则表达式是一个特殊的字符序列,它能帮助你方便的检查一个字符串是否与某种模式匹配。 Python 自1.5版本起增加了re 模块,它提供 Perl 风格的正...

python 用opencv调用训练好的模型进行识别的方法

此程序为先调用opencv自带的人脸检测模型,检测到人脸后,再调用我自己训练好的模型去识别人脸,使用时更改模型地址即可 #!usr/bin/env python import cv2...

python编程实现归并排序

python编程实现归并排序

因为上个星期leetcode的一道题(Median of Two Sorted Arrays)所以想仔细了解一下归并排序的实现。 还是先阐述一下排序思路: 首先归并排序使用了二分法,归根...