Python asyncio实现无需等待响应的事件触发方案问询
事件驱动架构下Python asyncio实现触发inner后立即终止outer的可行性
在事件驱动架构下,存在outer和inner两个函数,outer调用inner但无需获取其返回值,希望触发inner请求后立即终止outer。请问能否通过Python asyncio实现该需求?是否只需不使用await关键字即可?
示例代码
async def outer(): inner() return
对比写法
async def outer(): await inner() # not blocked by inner...but no remaining steps to perform return
补充实际示例
import time def inner(): print('inner started') time.sleep(5) print('inner complete') async def outer(): print('outer started') inner() print('outer complete') def next_(): print('next started') print('next complete')
场景一执行情况
执行代码:
outer() next_()
输出:
next started next complete /var/folders/p9/b46sgf393ys74l8dsh5fxyc80000gr/T/ipykernel_1113/3300557029.py:16: RuntimeWarning: coroutine 'outer' was never awaited RuntimeWarning: Enable tracemalloc to get the object allocation traceback
场景二执行情况
执行代码:
await outer() next_()
输出:
outer started inner started inner complete outer complete next started next complete
目前看来似乎无法在触发inner后立即终止outer(注:使用Jupyter notebook,可能对异步操作处理异常)。
有人可能会质疑“这有什么意义?让outer await inner再调用next_即可”——但考虑无服务器函数A和B的场景,若A不需要B的结果,等待会无端增加A的计算成本。
内容的提问来源于stack exchange,提问作者jbuddy_13
相关产品推荐
相关产品推荐

