asyncio

asyncio及其接口

2025年5月2日
python
202505, asyncio

协程 # import asyncio async def one(): return 1 async def greet(): await asyncio.sleep(2) return 'Hello world' async def main(): res1 = await one() res2 = await greet() print(res1) print(res2) asyncio.run(main()) Task # Task的cancelled接口 # import asyncio async def c(): return 1 async def main(): task = asyncio.create_task(c()) await task print(task.cancelled()) asyncio.run(main()) create_task # create_task() 方法用于创建一个新的 Task 对象,并将其添加到事件循环中。不会直接启动任务,直到遇到一个await import asyncio async def one(): return 1 async def greet(timeout): print('run', timeout) await asyncio. ...