python中利用Future对象回调别的函数示例代码

yipeiwu_com6年前Python基础

前言

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

Future对象也可以像协程一样,当它设置完成结果时,就可以立即进行回调别的函数

例子如下:

import asyncio 
import functools 
 
 
def callback(future, n): 
 print('{}: future done: {}'.format(n, future.result())) 
 
 
async def register_callbacks(all_done): 
 print('registering callbacks on future') 
 all_done.add_done_callback(functools.partial(callback, n=1)) 
 all_done.add_done_callback(functools.partial(callback, n=2)) 
 
 
async def main(all_done): 
 await register_callbacks(all_done) 
 print('setting result of future') 
 all_done.set_result('the result') 
 
 
event_loop = asyncio.get_event_loop() 
try: 
 all_done = asyncio.Future() 
 event_loop.run_until_complete(main(all_done)) 
finally: 
 event_loop.close() 

输出结果如下:

registering callbacks on future
setting result of future
1: future done: the result
2: future done: the result

在这个例子里,先调用函数add_done_callback()来注册一个回调函数,由于只支持一个参数,使用functools.partial来作一个封装。当set_result()函数调用之后,就立即进行回调函数的运行。

总结

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

相关文章

pandas dataframe添加表格框线输出的方法

pandas dataframe添加表格框线输出的方法

将dataframe添加到texttable里面,实现格式化输出。 data=[{"name":"Amay","age":20,"result":80}, {"name":"T...

python redis连接 有序集合去重的代码

python redis连接 有序集合去重的代码如下所述: # -*- coding: utf-8 -*- import redis from constant import re...

python 不关闭控制台的实现方法

直接打开dos窗口,再执行python程序 在脚本的最后一行后面添加:raw_input()语句,这样直到按下回车键,窗口才关闭。 使用time模块的sleep函数,它有一个参数,传入数...

Python读取mat文件,并转为csv文件的实例

初学Python,遇到需要将mat文件转为csv文件,看了很多博客,最后找到了解决办法,代码如下: #方法1 from pandas import Series,DataFrame...

python读取csv文件并把文件放入一个list中的实例讲解

如下所示: #coding=utf8 ''' 读取CSV文件,把csv文件放在一份list中。 ''' import csv class readCSV(object): def...