下面的例子演法了怎么样从协程里返回一个值:
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()方法来执行协程到结束。