Python协程返回值获取方法详解
本文介绍在Python中如何通过asyncio库从协程获取返回值。核心步骤包括使用get_event_loop()获取事件循环对象,并调用run_until_complete()执行协程直至完成,从而捕获协程返回的具体结果。
以下示例演示了如何从协程中获取返回值:
import asyncio
async def coroutine():
print('in coroutine')
return 'result'
event_loop = asyncio.get_event_loop()
try:
return_value = event_loop.run_until_complete(
coroutine()
)
print('it returned: {!r}'.format(return_value))
finally:
event_loop.close()
运行结果如下所示:
in coroutine it returned: 'result'
在该示例中,首先利用asyncio库提供的get_event_loop()方法获取事件循环对象,随后通过调用run_until_complete()方法执行协程直至其结束。
以上内容即为Python中从协程返回值的完整示例,供读者参考。
免责声明:本文内容仅供参考,不代表本站观点。转载或引用请注明出处。









