python里协程的概念

24 阅读1分钟

在python里也存在async和await,代码如

async def test():
  print('test')
  return "test"
if __name__ == '__main__':
  t = test()
  print(f"返回的协程对象:{t}") //返回的协程对象:<coroutine object test at 0x7fdbfd175cc0>

那我们如何把里面的数据解析出来呢就需要用到asyncio来协助我们 代码修改成

import asyncio
async def test():
  print('test')
  return "test"
if __name__ == '__main__':
  # t = test()
  # print(f"返回的协程对象:{t}")
  result = asyncio.run(test()) 
  print("result",result)//test

此时返回的结果就会是async返回的值 综上 1、asyncio.run可以用来执行协程,可以用来获取协程(async)函数的值