首页
学习
活动
专区
工具
TVP
发布
您找到你想要的搜索结果了吗?
是的
没有找到

python asyncio 异步 IO - 协程(Coroutine)与运行

前言 Python 在 3.5 版本中引入了关于协程的语法糖 async 和 await, 在 python3.7 版本可以通过 asyncio.run() 运行一个协程。...RuntimeWarning: Enable tracemalloc to get the object allocation traceback 在函数前面加了async,这就是一个协程了,运行的时候需使用asyncio.run...{time.time()}') await asyncio.sleep(3) print(f'------hello end : {time.time()} ----') # 运行 asyncio.run...1646009849.5220373 ------hello end : 1646009852.5258074 ---- 协程运行三种机制 要真正运行一个协程,asyncio 提供了三种主要机制: asyncio.run...通过前面第一个示例,知道了asyncio.run()来运行一个协程,接着看 await 等待的使用 import asyncio import time async def fun_a():

1.4K10

Python协程-asyncio、asyncawait

await 语句执行可等待对象(Coroutine、Task、Future) 使用 asyncio.create_task 创建任务,将异步函数(协程)作为参数传入,等待event loop执行 使用 asyncio.run...await task2 print("task2 结束") if __name__ == "__main__": start = time.perf_counter() asyncio.run...解释: 1、asyncio.run(main()),程序进入main()函数,开启事件循环 2、创建任务task1、task2并进入事件循环等待运行 3、输出准备开始 4、执行await task1,用户选择从当前主任务中切出...await asyncio.gather(a(), b()) if __name__ == "__main__": start = time.perf_counter() asyncio.run...url) # await会将程序阻塞在这里,进入被调用的协程函数,执行完毕后再继续 start = time.perf_counter() # pip install nest-asyncio asyncio.run

3.1K10
领券