Python Asyncio如何将一个异步函数的返回值传递给另一函数
解决方案
首先修正原代码的两处基础错误:
resp.text()返回的是字符串类型,无法通过键名直接取值,需要替换为await resp.json()解析为字典格式- 不要使用
print作为自定义异步函数名,会覆盖Python内置的print方法,下文统一改为print_result
方案1:单任务串行执行(逻辑最直观,适配现有循环结构)
因为print_result依赖check的返回值,二者无法直接并发执行,调整main函数逻辑,先等待check执行完成拿到返回值,符合条件再调用print_result:
import asyncio import aiohttp async def check(i): async with aiohttp.ClientSession() as session: url = f'https://pokeapi.co/api/v2/pokemon/{i}' async with session.get(url) as resp: data = await resp.json() # 用get方法避免键不存在抛出异常 if data.get('state') == 'yes': return data['state'] async def print_result(check_res): print(check_res) await asyncio.sleep(0) async def main(): for i in range(0,5): check_res = await check(i) # 仅check条件成立有返回值时,调用print_result if check_res: await asyncio.gather(print_result(check_res)) if __name__ == "__main__": asyncio.run(main())
方案2:全量并发执行(保留Asyncio高并发特性)
如果不需要按i的顺序执行,想同时发起所有请求提升性能,可以把单个i对应的整套逻辑封装为独立协程,再批量并发执行:
# check、print_result函数和上述代码一致 async def task_wrapper(i): check_res = await check(i) if check_res: await print_result(check_res) async def main(): tasks = [task_wrapper(i) for i in range(0,5)] await asyncio.gather(*tasks)
两种方案都保留了你原有的Asyncio异步结构,可根据是否需要并发选择使用。
内容的提问来源于stack exchange,提问作者Mark
相关产品推荐
相关产品推荐

