Python并发编程:异步编程(asyncio模块)③

302 阅读4分钟

2024-07-09_175549.png

1. 引言

Python 的异步编程越来越受到开发者的重视,尤其是在需要处理 I/O 密集型任务时。asyncio 是 Python 标准库中的一个模块,旨在编写并发代码。通过 asyncio,可以轻松地管理大量的 I/O 操作,如网络请求、文件读取等,提升程序的性能和响应速度。

本文将详细介绍 Python 的 asyncio 模块,包括其基础概念、核心组件、常用功能等,最后附上一个综合的示例,并运行示例以展示实际效果。

2. 基础概念

2.1 同步与异步

同步编程中,任务按顺序执行,当前任务未完成时,后续任务必须等待。异步编程则允许任务在等待时挂起,其他任务可以继续执行,提高了效率。

2.2 协程

协程是一种比线程更轻量级的并发单元。与线程不同,协程由用户代码调度,不依赖操作系统。Python 中使用 async def 定义协程函数,await 用于挂起协程等待结果。

2.3 事件循环

事件循环是 asyncio 的核心,它负责调度和执行协程。通过事件循环,可以实现非阻塞 I/O 操作。

3. 核心组件

3.1 协程函数

协程函数使用 async def 定义,调用时返回一个协程对象,需通过 await 执行。

import asyncio

async def my_coroutine():
    print("Hello, asyncio!")

# 创建事件循环并运行协程
asyncio.run(my_coroutine())

3.2 await 关键字

await 用于挂起协程,等待一个异步操作完成后继续执行。

import asyncio

async def fetch_data():
    await asyncio.sleep(2)
    return "Data fetched"

async def main():
    data = await fetch_data()
    print(data)

asyncio.run(main())

3.3 任务(Task)

任务是对协程的进一步封装,用于在事件循环中调度协程。通过 asyncio.create_task 创建任务。

import asyncio

async def my_coroutine():
    await asyncio.sleep(1)
    print("Task completed")

async def main():
    task = asyncio.create_task(my_coroutine())
    await task

asyncio.run(main())

3.4 并发执行

asyncio.gatherasyncio.wait 用于并发执行多个协程。

import asyncio

async def task1():
    await asyncio.sleep(1)
    print("Task 1 completed")

async def task2():
    await asyncio.sleep(2)
    print("Task 2 completed")

async def main():
    await asyncio.gather(task1(), task2())

asyncio.run(main())

3.5 异步上下文管理器

asyncio 支持异步上下文管理器,使用 async with 关键字管理异步资源。

import asyncio

class AsyncContextManager:
    async def __aenter__(self):
        print("Enter context")
        return self

    async def __aexit__(self, exc_type, exc, tb):
        print("Exit context")

    async def do_something(self):
        await asyncio.sleep(1)
        print("Doing something")

async def main():
    async with AsyncContextManager() as manager:
        await manager.do_something()

asyncio.run(main())

4. 常用功能

4.1 异步 I/O 操作

asyncio 提供了多种异步 I/O 操作,如网络请求、文件读取等。

4.1.1 异步网络请求

import asyncio
import aiohttp

async def fetch_url(session, url):
    async with session.get(url) as response:
        return await response.text()

async def main():
    async with aiohttp.ClientSession() as session:
        html = await fetch_url(session, "https://www.example.com")
        print(html)

asyncio.run(main())

4.1.2 异步文件读取

import asyncio
import aiofiles

async def read_file(file_path):
    async with aiofiles.open(file_path, 'r') as f:
        contents = await f.read()
    return contents

async def main():
    contents = await read_file("example.txt")
    print(contents)

asyncio.run(main())

4.2 异步生成器

异步生成器允许在迭代过程中使用 await 关键字。

import asyncio

async def async_generator():
    for i in range(5):
        await asyncio.sleep(1)
        yield i

async def main():
    async for value in async_generator():
        print(value)

asyncio.run(main())

4.3 超时控制

asyncio.wait_for 用于设置协程的超时时间。

import asyncio

async def my_coroutine():
    await asyncio.sleep(5)
    return "Task completed"

async def main():
    try:
        result = await asyncio.wait_for(my_coroutine(), timeout=3)
        print(result)
    except asyncio.TimeoutError:
        print("Task timed out")

asyncio.run(main())

4.4 取消任务

任务可以被取消,通过 task.cancel() 方法实现。

import asyncio

async def my_coroutine():
    try:
        await asyncio.sleep(5)
    except asyncio.CancelledError:
        print("Task was cancelled")

async def main():
    task = asyncio.create_task(my_coroutine())
    await asyncio.sleep(1)
    task.cancel()
    await task

asyncio.run(main())

5. 综合详细的例子

5.1 示例:异步爬虫

我们将实现一个简单的异步爬虫,从多个网页中并发地抓取内容,并解析其中的标题。

import asyncio
import aiohttp
from bs4 import BeautifulSoup

class AsyncCrawler:
    def __init__(self, urls):
        self.urls = urls

    async def fetch(self, session, url):
        try:
            async with session.get(url) as response:
                return await response.text()
        except Exception as e:
            print(f"Failed to fetch {url}: {e}")
            return None

    async def parse(self, html):
        soup = BeautifulSoup(html, 'html.parser')
        title = soup.find('title').text if soup.title else 'No Title'
        return title

    async def crawl(self, url):
        async with aiohttp.ClientSession() as session:
            html = await self.fetch(session, url)
            if html:
                title = await self.parse(html)
                print(f"URL: {url}, Title: {title}")

    async def run(self):
        tasks = [self.crawl(url) for url in self.urls]
        await asyncio.gather(*tasks)

if __name__ == "__main__":
    urls = [
        'https://example.com',
        'https://example.org',
        'https://example.net'
    ]
    crawler = AsyncCrawler(urls)
    asyncio.run(crawler.run())

5.2 运行结果

URL: https://example.com, Title: Example Domain
URL: https://example.org, Title: Example Domain
URL: https://example.net, Title: Example Domain

6. 总结

本文详细介绍了 Python 的 asyncio 模块,包括其基础概念、核心组件、常用功能等,并通过多个示例展示了如何在实际项目中应用这些技术。通过学习这些内容,您应该能够熟练掌握 Python 中的异步编程,提高编写并发程序的能力。

异步编程可以显著提高程序的响应速度和并发处理能力,但也带来了新的挑战和问题。在使用 asyncio 时,需要注意合理设计协程和任务,避免阻塞操作,并充分利用事件循环和异步 I/O 操作。

希望本文能帮助您更好地理解和掌握 Python 中的异步编程。如果您有任何问题或建议,请随时在评论区留言交流。


欢迎点赞|关注|收藏|评论,您的肯定是我创作的动力