网络编程
位置:首页>> 网络编程>> Python编程>> python中利用Future对象回调别的函数示例代码

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

作者:caimouse  发布时间:2021-09-28 13:03:43 

标签:python,future对象,回调函数

前言

本文主要给大家介绍了关于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()函数调用之后,就立即进行回调函数的运行。

来源:http://blog.csdn.net/caimouse/article/details/77869636

0
投稿

猜你喜欢

手机版 网络编程 asp之家 www.aspxhome.com