协程asyncio入门案例 2

协程对象

复制代码
obj = func()  # 创建一个协程对象, 但不会执行
复制代码
import asyncio


async def func():
    print("hello world")


obj = func()  # 创建一个协程对象, 但不会执行
"""
DeprecationWarning: There is no current event loop
  loop=asyncio.get_event_loop()
  Python 3.70及以上版本中,asyncio.get_event_loop()的行为发生了变化,若未显式创建事件循环,则会抛出警告。
该警告不影响程序运行,但表明代码不符合最新最佳实践。
  loop=asyncio.get_event_loop()
  loop.run_until_complete(obj)
"""
# 方式一:
# asyncio.run(obj)

"""
方式二:
简要解释报错原因: DeprecationWarning提示当前没有事件循环,
asyncio.get_event_loop()在Python 3.70+中已被弃用,
推荐使用asyncio.run()
或asyncio.new_event_loop()。
"""
# 手动创建并运行事件循环
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
try:
    loop.run_until_complete(obj)
finally:
    loop.close()

协程事件

复制代码
obj = func()  # 创建一个协程对象, 但不会执行,想要执行,需要协程事件
复制代码
Python 3.70及以上版本
复制代码
asyncio.run(obj)

"""
相当于执行了之前python老版本,这两行代码
loop=asyncio.get_event_loop()
loop.run_until_complete(obj)
"""

或者

复制代码
# 手动创建并运行事件循环
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
try:
    loop.run_until_complete(obj)
finally:
    loop.close()

await

await+可等待的对象(协程对象、Future、task对象->IO等待)

await 协程对象

复制代码
import asyncio

async def other():
    print("start")
    await asyncio.sleep(2)
    print("end")
    return "done"

async def func():
    print("hello world")
    result = await other()
    print("result",result)

if __name__ == '__main__':
    asyncio.run(func())

await task对象

案例1

复制代码
import asyncio
import time


async def func():
    print("start")
    await asyncio.sleep(3)
    print("end")
    return "done"


async def main():
    print("main")
    # 创建任务对象,添加到事件循环中
    task1 = asyncio.create_task(func())
    task2 = asyncio.create_task(func())
    print("main end")

    ret1 = await task1
    ret2 = await task2
    print(ret1, ret2)


start_time = time.time()
asyncio.run(main())
end_time = time.time()
print("执行时间", end_time - start_time)

案例2

复制代码
import asyncio
import time


async def func():
    print("start")
    await asyncio.sleep(3)
    print("end")
    return "返回值"


async def main():
    print("main")
    # 创建任务对象,添加到事件循环中
    task_list = [
        # name给任务命名,方便查看
        asyncio.create_task(func(), name="任务1"),
        asyncio.create_task(func(), name="任务2")
    ]
    # timeout默认为None,一般不设置
    done, pending = await asyncio.wait(task_list, timeout=None)
    print(done)
    print("-----")
    print(pending)
    for task in done:
        # 获取任务返回值
        print(task.result())


start_time = time.time()
asyncio.run(main())
end_time = time.time()
print("执行时间", end_time - start_time)

await asyncio.Future对象

Task继承Future对象,Task对象内部await结果的处理基于Future对象来的。

一般使用Task,Future用的少。

协程异步编程+MySQL(不支持异步),解决方法【线程、进程做异步编程】

复制代码
import time
import asyncio
import concurrent.futures


def func():
    time.sleep(3)
    return "done"


async def main():
    loop = asyncio.get_running_loop()
    #func是一个普通函数,需要用loop.run_in_executor方法包装成asyncio.Future对象才能运行
    fut = loop.run_in_executor(None, func)
    result = await fut
    print('default thread pool', result)


asyncio.run(main())
相关推荐
用户7783366132115 小时前
用 React Hook 封装搜索数据:useSerp 的防抖、缓存与错误处理
python·api
65岁退休Coder9 小时前
LangGraph v1.2.9 节点容错策略 & 流式输出 & 持久化记忆管理
后端·python·langchain
ikun_文11 小时前
Django框架路由Router的使用
python·pycharm·django
IvanCodes11 小时前
Python 基础语法(二):字符串与常用操作
python
昭昭日月明12 小时前
LangChain 生态:从链到代理,开发者需要掌握的三大核心
python·langchain·agent
Csvn12 小时前
🐍 Day 8:面向对象编程
后端·python
程序员天天困12 小时前
向量检索不准怎么办:混合检索与 Rerank 重排序召回优化实战
后端·python·ai编程
alphaTao13 小时前
LeetCode 每日一题 2026/8/24-2026/8/30
python·算法·leetcode
苏灿烤鱼13 小时前
当 AI Agent 遇见真实科学环境:深度拆解 Scientific Agent Skills,把"聊天机器人"变成"AI 科学家"
python·开源·agent
张文君13 小时前
ubuntu26.04坏道坏块分区隔离急速版260831-V0.12
linux·python