done, pending = await asyncio.wait(tasks, return_when=asyncio.FIRST_COMPLETED) print(f’The first task completed was {done.pop().get_name()}’) asyncio.run(main()) Output: The first task completed was 4 asyncio.
print(context) async def delay_return(time:float,context:str): await asyncio.sleep(time) return context asyncio.TaskGroup 在Python 3.10版本引入,在本次案例中替代asyncio.gather() async def async_taskgroups(): async with asyncio.TaskGroup() as tg: task1 = tg.create_task(delay_return(1,"sign...
# await asyncio.gather/wait 并发执行 return_a, return_b = await asyncio.gather(a(), b()) # return_a是协程a的返回值 done, pending = await asyncio.wait([a(), b()]) # task.result()获得协程返回值 asyncio.sleep(delay, result=None, *, loop=None) -> coro # 休眠5s 1. 2. 3. 4...
import asyncio import time async def say_after(delay, what): print(f"Begin {what}, at {time.strftime('%X')}") await asyncio.sleep(delay) print(f"End {what}, at {time.strftime('%X')}") async def main(): task1 = asyncio.create_task(say_after(3, 'First')) task2 = asyncio.cr...
一、最简协程:asyncio.run() 函数用来运行最高层级的入口点。 二、asyncio.run()内部则使用await关键字来调用。 三、并发协程asyncio.create_task()和asyncio.TaskGroup 四、可等待对象await 五、创建任务asyncio.create_task() 六、任务组TaskGroup 七、休眠asyncio.sleep() ...
tasks.append(task) loop = asyncio.get_event_loop() loop.run_until_complete(asyncio.wait(tasks))print('总耗时:',time.time()-start) 6. uvloop加速 uvloop基于libuv,libuv是一个使用C语言实现的高性能异步I/O库,uvloop用来代替asyncio默认事件循环,可以进一步加快异步I/O操作的速度。
1', 8888) addr = server.sockets[0].getsockname() print(f'Serving on {addr}') async with server: await server.serve_forever()async def main(): task = asyncio.create_task(tcp_server_task()) await taskasyncio.run(main())可以看到代码并不是很多,创建一个简单的 TCP 服务...
group2 = asyncio.gather(*tasks2) results1, results2 = await asyncio.gather(group1, group2) print(results1, results2) 在某些定制化任务需求的时候,可以使用 wait: # Python3.8 版本后,直接向 wait() 传入协程对象已弃用,必须手动创建 Task
async with asyncio.TaskGroup as tg: tg.create_task(t1) tg.create_task(t2) except* ValueError as e: pass# 忽略所有的 ValueErrors 在该示例中,即使t1出错了,任务t2也会继续执行。 后记 这些是Python 3.11中一些有趣的新特性,如果你想了解更多新特性,可以在官方文档中查看[2] 。
importasyncio# 协程函数asyncdefdo_some_work(x):print('Waiting: ',x)awaitasyncio.sleep(x)return'Done after{}s'.format(x)# 协程对象coroutine1=do_some_work(1)coroutine2=do_some_work(2)coroutine3=do_some_work(4)# 将协程转成task,并组成listtasks=[asyncio.ensure_future(coroutine1),asyncio....