Python call callback after async function is done(异步函数完成后的Python回调)
本文介绍了异步函数完成后的Python回调的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试在异步函数运行完成后调用回调
以下是我尝试执行的操作的示例:
import asyncio
async def asyncfunction():
print('Hello')
await asyncio.sleep(10)
print('World')
return 10
def callback(n):
print(f'The async function returned: {n}')
loop = asyncio.get_event_loop()
# Will block the print until everything is done
callback(loop.run_until_complete(asyncfunction()))
print('Hey')
这是它的作用:
Hello
World
The async function returned: 10
Hey
我希望它这样做
编辑:"嘿"的位置并不重要,只要它不需要等待异步函数完成
Hello
Hey
World
The async function returned: 10
编辑:经过一些测试,我找到了一种做我想做的事情的方法,尽管我不知道这是否是最好的方法
import asyncio
import threading
async def asyncfunction():
print('Hello')
await asyncio.sleep(10)
print('World')
return 10
def callback(n):
print(f'The async function returned: {n}')
def wrapper(loop):
callback(loop.run_until_complete(asyncfunction()))
loop = asyncio.get_event_loop()
thr = threading.Thread(target=wrapper,args=(loop,))
thr.start()
print('Hey')
推荐答案
将线程与Asyncio一起使用令人困惑,而且很可能不是您想要的。run_until_complete
是阻塞调用之一,很可能是asyncio
程序中的最后一条语句。
要在调用异步函数后添加代码,只需创建创建包装
async def myfunc():
n = await asyncfunction()
callback(n)
loop.run_until_complete(myfunc()) # from python 3.7, asyncio.run(myfunc())
如果您只想安排一些代码异步运行并继续执行其他操作,请创建一个任务并在结束时等待
async def a_main():
task = asyncio.ensure_future(myfunc()) # from python 3.7, asyncio.create_task(...)
print("Hey")
# Anything else to run
await task # wait for the task to complete
loop.run_until_complete(a_main())
这篇关于异步函数完成后的Python回调的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
沃梦达教程
本文标题为:异步函数完成后的Python回调


基础教程推荐
猜你喜欢
- Python 的 List 是如何实现的? 2022-01-01
- 症状类型错误:无法确定关系的真值 2022-01-01
- 如何在 Python 中检测文件是否为二进制(非文本)文 2022-01-01
- 合并具有多索引的两个数据帧 2022-01-01
- 使用 Google App Engine (Python) 将文件上传到 Google Cloud Storage 2022-01-01
- 哪些 Python 包提供独立的事件系统? 2022-01-01
- 如何在Python中绘制多元函数? 2022-01-01
- 使 Python 脚本在 Windows 上运行而不指定“.py";延期 2022-01-01
- 使用Python匹配Stata加权xtil命令的确定方法? 2022-01-01
- 将 YAML 文件转换为 python dict 2022-01-01