协程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())
相关推荐
Risehuxyc1 分钟前
PHP能不能在参数里放匿名函数
开发语言·php
码云社区12 分钟前
Java家政服务系统源码:人员技能、服务范围与多商家业务落地
java·开发语言·家政服务·家政小程序·家政系统
ch62338 分钟前
🚀 从零构建本地文档智能审查 Agent:Vibe Coding 实战指南
python
FRing031 小时前
vue3干货总结3(defineOptions(Vue3.3)、defineModel(Vue3.4)、Pinia)
开发语言·前端·vue.js·vue3
摇滚侠1 小时前
《On Java 中文版 基础卷》阅读笔记 接口 18
java·笔记·python
Thanks_ks2 小时前
AI Agent 开发入门:用 Function Calling 让大模型学会 “动手干活”,附订单查询机器人实战
python·ai·大模型·openai·agent·通义千问·mcp
专注仿真2 小时前
智能体训练之模仿学习:GAIL 算法详解与实战
python·算法·仿真·多智能体强化学习·afsim智能体训练
whitelbwwww2 小时前
CUDA C++实战--中级
开发语言·前端·c++
FungLeo3 小时前
FengCMS · PHP+MySQL 升级实录 · 内容写入一致性:锁等待超时与跨模型子树删除竞态
开发语言·mysql·php·工程实践·fengcms
databook3 小时前
处理一批 PDF,怎么算真的处理完了
后端·python