协程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())
相关推荐
尹人入圣37 分钟前
目前热门的IP驱动产业新场景新工具
网络·python·网络协议·tcp/ip
开开心心_Every1 小时前
快速隐藏程序工具自定义快捷键一键切换
java·开发语言·前端·spring·智能手机·word·intellij-idea
chenbingjie_c1 小时前
C++ 多态完全指南:从虚函数重写到虚函数表原理
开发语言·c++
Nuanyt1 小时前
Agent 学习笔记(下篇三):上线工程、进阶选择与操作界面(Stage 7 / 7.5 / 8 + 延伸路线)
笔记·python·学习·memory·aiagent·harness
吴卫斌1 小时前
定投ETF实战指南(四):行业/主题ETF——定投的“进攻端“
开发语言·python·股票·量化
2601_967987372 小时前
Python——入门级(定义功能def函数)
python·函数·可变参数·默认参数·关键字参数
超级架构师2 小时前
PRAXO-CORE 2.5.0:用 conformance 和显式边界构建 Go Agent 框架
开发语言·人工智能·后端·golang·ai编程·智能体框架·praxo-core
叼烟扛炮3 小时前
Linux 学习笔记(四十三):网络编程进阶——自定义协议解决 TCP 粘包与守护进程
linux·开发语言·网络·笔记·tcp/ip
LMT流氓兔4 小时前
第五单元——第十六课:给书店助手加上网页界面
java·开发语言·jvm·人工智能·oracle·langchain·1024程序员节
专注仿真4 小时前
梯度提升类(XFBoost)算法详解与代码实例
开发语言·人工智能·python·算法·大模型训练·控制算法