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

简介: 本文详细介绍了 Python 的 asyncio 模块,包括其基础概念、核心组件、常用功能等,并通过多个示例展示了如何在实际项目中应用这些技术。通过学习这些内容,您应该能够熟练掌握 Python 中的异步编程,提高编写并发程序的能力。异步编程可以显著提高程序的响应速度和并发处理能力,但也带来了新的挑战和问题。在使用 asyncio 时,需要注意合理设计协程和任务,避免阻塞操作,并充分利用事件循环和异步 I/O 操作。

一、引言

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


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

二、基础概念

2.1 同步与异步

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

2.2 协程

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

2.3 事件循环

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

三、核心组件

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.gather 和 asyncio.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.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.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

六、总结

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


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


作者:Rjdeng

链接:https://juejin.cn/post/7398198236160655397

相关文章
|
15天前
|
数据采集 API 数据库
探索Python中的异步编程:从理解到实践
【8月更文挑战第30天】在Python世界中,异步编程是一个既神秘又强大的概念。它像是给程序装上了翅膀,让原本缓慢、阻塞的操作变得迅速而流畅。本文将带你走进异步编程的世界,从基本的概念讲起,通过实例演示如何运用Python的异步特性来提升程序的性能和响应速度。我们将一步步构建一个简易的异步Web爬虫,让你在实践中感受异步编程的魅力。
|
4天前
|
数据采集 开发者 Python
探索Python中的异步编程:从基础到实战
【9月更文挑战第9天】本文将带你进入Python异步编程的世界,从理解其核心概念开始,逐步深入到实际应用。我们将一起构建一个小型的异步Web爬虫,通过实践学习如何在不阻塞主线程的情况下并发处理任务,优化程序性能。文章不仅包含理论知识,还提供代码示例,让读者能够动手实践,深刻理解异步编程的力量。
26 12
|
4天前
|
Java Serverless Python
探索Python中的并发编程与`concurrent.futures`模块
探索Python中的并发编程与`concurrent.futures`模块
11 4
|
9天前
|
数据采集 Python
探索Python中的异步编程:从基础到实战
【9月更文挑战第4天】在Python的海洋中,异步编程犹如一艘快艇,让你的代码在执行效率和响应速度上破浪前行。本文将带你从理解“异步”这一概念出发,深入到Python的asyncio库的使用,再到构建一个实际的异步Web爬虫项目,体验异步编程的魅力。我们将避开枯燥的理论,通过生动的比喻和直观的代码示例,让异步编程的知识活灵活现。
|
14天前
|
设计模式 数据库 开发者
探索Python中的异步编程:从理解到实践
【8月更文挑战第31天】本文旨在通过浅显易懂的语言和具体代码示例,为读者揭开Python异步编程的神秘面纱。我们将从基础概念入手,逐步深入到实战应用,让读者能够不仅理解异步编程的内涵,还能掌握其在实际项目中的应用技巧。无论你是编程新手还是有经验的开发者,这篇文章都将为你提供有价值的见解和指导。
|
15天前
|
设计模式 调度 Python
Python中的异步编程:从理解到实践打造你的个人博客——从零开始的指南
【8月更文挑战第30天】本文将带你深入探索Python的异步编程世界,从基础概念到实际应用,一步步揭示如何通过asyncio库提升程序的响应性和效率。我们将通过实际代码示例,展示如何创建异步任务、管理事件循环以及处理并发操作,让你的代码运行得更加流畅和高效。
|
14天前
|
设计模式 调度 开发者
探索Python中的异步编程:从基础到实战
【8月更文挑战第31天】本文将带你进入Python异步编程的世界,通过浅显易懂的语言和实例,让你理解异步编程的概念、优势及应用场景。我们将一起学习asyncio库的基础用法,并通过代码示例深入探讨异步IO操作、任务管理以及异常处理等关键知识点。无论你是初学者还是有一定经验的开发者,这篇文章都将为你打开一扇通往高效异步编程的大门。
|
14天前
|
数据采集 数据处理 开发者
探索Python中的异步编程:从基础到高级
【8月更文挑战第31天】在数字世界中,速度和效率至关重要。Python的异步编程提供了一种机制,使得程序可以同时处理多个任务,而无需等待某个任务完成。本文将带你了解异步编程的概念,并通过实际代码示例,展示如何在Python中实现异步功能。我们将一起构建一个简单的异步Web爬虫,以实践理论知识并体验异步带来的性能提升。
|
16天前
|
Python
如何在 Python 中导入模块
【8月更文挑战第29天】
19 1
|
14天前
|
设计模式 调度 开发者
探索Python中的异步编程:从基础到实战
【8月更文挑战第31天】本文将带领读者深入理解Python中的异步编程,从其核心概念、工作原理到实际应用。通过具体代码示例,展示如何在Python项目中实现高效的并发处理,解决实际开发中的性能瓶颈问题。适合具有一定Python基础的开发者阅读,旨在提升编程效率与项目性能。