欢迎访问宙启技术站
智能推送

Python中如何处理异步任务

发布时间:2023-12-18 11:24:31

在Python中,可以使用协程和异步库来处理异步任务。在Python 3.5及以上版本中,可以使用内置的asyncio库来实现异步编程。下面是一个处理异步任务的示例代码:

import asyncio

async def fetch(url):
    print(f"Start fetching {url}")
    await asyncio.sleep(1)  # 模拟耗时操作,如网络请求
    print(f"Fetch {url} completed")

async def main():
    tasks = [
        asyncio.create_task(fetch("https://example.com")),
        asyncio.create_task(fetch("https://google.com")),
        asyncio.create_task(fetch("https://facebook.com"))
    ]
    await asyncio.gather(*tasks)  # 等待所有任务完成

asyncio.run(main())

在上面的代码中,fetch函数是一个异步函数,用于模拟网络请求。await asyncio.sleep(1)语句表示在异步任务中进行一个1秒的延迟,模拟耗时操作。main函数是主函数,用于调度异步任务。

main函数中,通过asyncio.create_task创建了三个异步任务,并将它们存储在tasks列表中。然后使用asyncio.gather(*tasks)语句等待所有任务完成。

最后,通过asyncio.run(main())语句运行主函数。

运行上述代码,会输出类似以下内容的结果:

Start fetching https://example.com
Start fetching https://google.com
Start fetching https://facebook.com
Fetch https://example.com completed
Fetch https://google.com completed
Fetch https://facebook.com completed

在输出结果中,可以看到三个异步任务按照创建的顺序被执行,并且它们是同时进行的(非阻塞)。

除了使用asyncio库,还可以使用第三方库aiohttp来处理异步的网络请求。aiohttp提供了更高级的功能和更方便的请求交互接口。以下是使用aiohttp库的示例代码:

import asyncio
import aiohttp

async def fetch(session, url):
    async with session.get(url) as response:
        print(f"Fetch {url} completed")

async def main():
    urls = [
        "https://example.com",
        "https://google.com",
        "https://facebook.com"
    ]
    async with aiohttp.ClientSession() as session:
        tasks = [asyncio.create_task(fetch(session, url)) for url in urls]
        await asyncio.gather(*tasks)  # 等待所有任务完成

asyncio.run(main())

在上面的代码中,fetch函数使用aiohttp库发送异步请求并获取响应。main函数中使用aiohttp.ClientSession来创建一个异步的HTTP会话,并在会话中执行异步请求。

main函数中,通过列表解析创建了多个异步任务,并使用asyncio.gather(*tasks)等待所有任务完成。

运行上述代码,会得到与前面代码类似的结果。

总结来说,处理异步任务的基本步骤是定义异步函数并使用asyncio.create_task创建任务,然后使用asyncio.gather来等待任务完成。可以使用内置的asyncio库或第三方库如aiohttp来处理异步任务。