协程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())
相关推荐
Warson_L13 小时前
Python `Annotated` 与 LangGraph Reducer 学习笔记
python
韩师傅13 小时前
海天线算法的前世今生
python·计算机视觉
韩师傅13 小时前
当你的甲方设备过烂,要如何快速出效果?
python·计算机视觉
Warson_L13 小时前
LangGraph的MessageState and HumanMessage
python
韩师傅14 小时前
当你的甲方吐槽天空不够蓝,你应该如何应对
python·计算机视觉
Warson_L14 小时前
python的类&继承
python
Warson_L14 小时前
类型标注/type annotation
python
ThreeS16 小时前
手搓MiniVLA全实战教程-一步一步用pytorch解释原理与思路
人工智能·python
金銀銅鐵18 小时前
[Python] 模 n 乘法的逆元计算器
python·数学·游戏