digmouse’s Ai journey

  • DeepSeek Agent
  • deepseek application
Ai无处不在
专注Ai Agent产品设计开发
  1. 首页
  2. python
  3. 正文

Asyncio-异步IO(Python)

25 2 月, 2025 281点热度 0人点赞

串行

import asyncio
import time

async def say_after(delay,what):
    await asyncio.sleep(delay)
    print(what)

async def main():
    print(f"started at {time.strftime('%X')}")
    await say_after(1,'hello') #await是等待say_after返回结果才能继续往下执行
    await say_after(2,'world')

    print(f"finished at {time.strftime('%X')}")

asyncio.run(main())

串行就是顺序执行

并行

import asyncio
import time

async def say_after(delay,what):
    await asyncio.sleep(delay)
    print(what)

async def main():
    task1=asyncio.create_task(say_after(1,'hello'))
    task2=asyncio.create_task(say_after(2,'world'))

    print(f"started at {time.strftime('%X')}")
    await task1
    await task2

    print(f"finished at {time.strftime('%X')}")

asyncio.run(main())

异步的核心是asyncio.create_task

参考资料:

https://docs.python.org/zh-cn/3.9/library/asyncio-task.html

标签: asyncio 异步
最后更新:25 2 月, 2025

digmouse

这个人很懒,什么都没留下

点赞

文章评论

razz evil exclaim smile redface biggrin eek confused idea lol mad twisted rolleyes wink cool arrow neutral cry mrgreen drooling persevering
取消回复

Archives

  • 2025 年 5 月
  • 2025 年 4 月
  • 2025 年 3 月
  • 2025 年 2 月
  • 2025 年 1 月

Categories

  • Ai Agent
  • Ai本地知识库
  • Ai资源
  • llamaindex
  • LLM
  • MCP
  • python
  • rerank model
  • Uncategorized

COPYRIGHT © 2025 digmouse’s Ai journey. ALL RIGHTS RESERVED.

Theme Kratos Made By Seaton Jiang