Python协程 async与await的用法

Python协程 async与await的用法

1. 使用await关键字

"""
Python协程使用

async
携程函数:python3.5之后使用 async def 函数名,定义的函数就叫携程函数。
携程对象:执行携程函数 函数名(),得到的就是携程对象。

await
await + 可等待对象(协程对象,Future,Task对象(IO等待))。
"""
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
    print("task add")
    await task2

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


if __name__ == '__main__':
    # loop = asyncio.get_event_loop()
    # loop.run_until_complete(main())

    # asyncio.run 等于上面的两行代码
    asyncio.run(main())

2. 添加任务列表

import asyncio
import time


async def func1():
    for i in range(5):
        print('协程1')
        time.sleep(1)


async def func2():
    for i in range(5):
        print('协程2')
        time.sleep(1)

# task可为列表,即任务列表
# task = func1()
task = [func1(), func2()]
# # 创建事件循环
loop = asyncio.get_event_loop()
# # 添加任务,直至所有任务执行完成
loop.run_until_complete(asyncio.wait(task))
# # 关闭事件循环
loop.close()
# # 事件循环关闭后,再次调用loop,将不会再次执行。
# asyncio.run(asyncio.wait(task))

3. 协程的应用

其实可以在函数的任务前面加上await,那么这个进程就会把当前的控制权交出,先执行其他任务。

import asyncio
import requests
import time


async def result(url):
    res = await request_url(url)
    print(url, res)


async def request_url(url):
    res = requests.get(url)
    print(url)
    await asyncio.sleep(2)
    print("execute_time:", time.time() - start)
    return res


url_list = ["https://www.csdn.net/",
            "https://blog.csdn.net/qq_43380180/article/details/111573642",
            "https://www.baidu.com/",
            ]

start = time.time()
print(f"start_time:{start}\n")

task = [result(url) for url in url_list]
loop = asyncio.get_event_loop()
loop.run_until_complete(asyncio.wait(task))

endtime = time.time() - start
print("\nendtime:", time.time())
print("all_execute_time:", endtime)

执行结果

start_time:1691118061.5575836

https://www.baidu.com/
https://www.csdn.net/
https://blog.csdn.net/qq_43380180/article/details/111573642
execute_time: 4.610013723373413
https://www.baidu.com/ <Response [200]>
execute_time: 4.610013723373413
https://www.csdn.net/ <Response [521]>
execute_time: 6.621567726135254
https://blog.csdn.net/qq_43380180/article/details/111573642 <Response [200]>

endtime: 1691118068.1791513
all_execute_time: 6.621567726135254

你可能感兴趣的:(python,开发语言,前端)