AttributeError: module ‘asyncio‘ has no attribute ‘run‘ 或者是 “create_task”

asyncio异步协程写法
在python3.7之前

async def f1(num):
    print("f1 start")
    await asyncio.sleep(num)
    print("f1 end")
async def f2(num):
    print("f3 start")
    await asyncio.sleep(num)
    print("f3 end")
async def f3(num):
    print("f3 start")
    await asyncio.sleep(num)
    print("f3 end")
async def main():
    print(int(time.time()))
    loop = asyncio.get_event_loop()
    task1 = loop.create_task(f1(1))         # create_task是asyncio.get_event_loop()创建
    task2 = loop.create_task(f2(2))
    task3 = loop.create_task(f3(3))
    await task1
    await task2
    await task3
    print(int(time.time()))
if __name__ == '__main__':
    loop = asyncio.get_event_loop()
    loop.run_until_complete(main())  
    loop.close()

python3.7之后(兼容3.7之前的)

async def f1(num):
     print("f1 start")
     await asyncio.sleep(num)
     print("f1 end")
 async def f2(num):
     print("f3 start")
     await asyncio.sleep(num)
     print("f3 end")
 async def f3(num):
     print("f3 start")
     await asyncio.sleep(num)
     print("f3 end")
 async def main():
     print(int(time.time()))
     task1 = asyncio.create_task(f1(1))    # 直接acyncio.create_task
     task2 = asyncio.create_task(f2(2))
     task3 = asyncio.create_task(f3(3))
     await task1
     await task2
     await task3
     # 上面是异步,下面同步
     # await f1(1) 
     # await f2(2) 
     # await f3(3) 
     print(int(time.time()))
 if __name__ == '__main__':
     asyncio.run(main())    # 直接asyncio.run 即可

输出

1623983932
f1 start
f3 start
f3 start
f1 end
f3 end
f3 end
1623983935
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值