Python asyncio核心原理与高阶应用全解析

 更新时间:2026年05月05日 11:43:12   作者:第一程序员  
这篇文章主要介绍了Python asyncio核心原理与高阶应用,asyncio是Python中强大的异步I/O框架,它允许我们编写高效的并发代码,通过掌握asyncio的高级应用,我们可以编写更加高效、响应迅速的应用程序,需要的朋友可以参考下

1. asyncio 基础

asyncio 是 Python 3.4+ 引入的异步 I/O 框架,它允许我们编写异步代码,提高程序的并发性能。

import asyncio
async def main():
    print("Hello")
    await asyncio.sleep(1)
    print("World")
# 运行异步函数
asyncio.run(main())

2. 高级 asyncio 技巧

2.1 任务管理

import asyncio
async def task1():
    await asyncio.sleep(1)
    print("Task 1 completed")
    return "Task 1 result"
async def task2():
    await asyncio.sleep(2)
    print("Task 2 completed")
    return "Task 2 result"
async def main():
    # 创建任务
    task1_obj = asyncio.create_task(task1())
    task2_obj = asyncio.create_task(task2())
    # 等待任务完成
    result1 = await task1_obj
    result2 = await task2_obj
    print(f"Results: {result1}, {result2}")
asyncio.run(main())

2.2 并发执行

import asyncio
async def fetch_data(id):
    await asyncio.sleep(1)
    return f"Data {id}"
async def main():
    # 并发执行多个任务
    results = await asyncio.gather(
        fetch_data(1),
        fetch_data(2),
        fetch_data(3)
    )
    print(f"Results: {results}")
asyncio.run(main())

2.3 超时处理

import asyncio
async def slow_operation():
    await asyncio.sleep(2)
    return "Operation completed"
async def main():
    try:
        # 设置超时
        result = await asyncio.wait_for(slow_operation(), timeout=1)
        print(f"Result: {result}")
    except asyncio.TimeoutError:
        print("Operation timed out")
asyncio.run(main())

2.4 事件循环

import asyncio
async def main():
    print("Hello")
    await asyncio.sleep(1)
    print("World")
# 获取事件循环
loop = asyncio.get_event_loop()
# 运行协程
loop.run_until_complete(main())
# 关闭事件循环
loop.close()

3. 实际应用场景

3.1 网络请求

import asyncio
import aiohttp
async def fetch_url(url):
    async with aiohttp.ClientSession() as session:
        async with session.get(url) as response:
            return await response.text()
async def main():
    urls = [
        "https://api.github.com",
        "https://api.example.com",
        "https://api.google.com"
    ]
    # 并发请求
    tasks = [fetch_url(url) for url in urls]
    results = await asyncio.gather(*tasks)
    for url, result in zip(urls, results):
        print(f"URL: {url}, Length: {len(result)}")
asyncio.run(main())

3.2 文件 I/O

import asyncio
async def read_file(filename):
    async with open(filename, 'r') as f:
        content = await f.read()
    return content
async def write_file(filename, content):
    async with open(filename, 'w') as f:
        await f.write(content)
async def main():
    # 读取文件
    content = await read_file('input.txt')
    print(f"Read content: {content}")
    # 写入文件
    await write_file('output.txt', content.upper())
    print("File written")
asyncio.run(main())

3.3 数据库操作

import asyncio
import asyncpg
async def main():
    # 连接数据库
    conn = await asyncpg.connect(
        host='localhost',
        port=5432,
        user='postgres',
        password='password',
        database='test'
    )
    # 执行查询
    rows = await conn.fetch('SELECT * FROM users')
    for row in rows:
        print(row)
    # 关闭连接
    await conn.close()
asyncio.run(main())

3.4 Web 服务器

import asyncio
from aiohttp import web
async def handle(request):
    name = request.match_info.get('name', "Anonymous")
    return web.Response(text=f"Hello, {name}!")
async def main():
    app = web.Application()
    app.add_routes([
        web.get('/', handle),
        web.get('/{name}', handle)
    ])
    runner = web.AppRunner(app)
    await runner.setup()
    site = web.TCPSite(runner, 'localhost', 8080)
    await site.start()
    print("Server started on http://localhost:8080")
    await asyncio.Event().wait()
asyncio.run(main())

4. 最佳实践

  • 使用 asyncawait:使用 async 定义异步函数,使用 await 等待异步操作完成。
  • 使用 asyncio.create_task:使用 asyncio.create_task 创建任务,实现并发执行。
  • 使用 asyncio.gather:使用 asyncio.gather 并发执行多个任务,收集结果。
  • 使用 asyncio.wait_for:使用 asyncio.wait_for 设置超时,避免任务无限等待。
  • 使用 async with:使用 async with 管理异步上下文,确保资源正确释放。
  • 避免阻塞操作:在异步函数中避免使用阻塞操作,如 time.sleep(),应使用 asyncio.sleep() 替代。
  • 合理使用事件循环:根据应用场景选择合适的事件循环运行方式。

5. 总结

asyncio 是 Python 中强大的异步 I/O 框架,它允许我们编写高效的并发代码。通过掌握 asyncio 的高级应用,我们可以编写更加高效、响应迅速的应用程序。

在实际应用中,asyncio 可以用于网络请求、文件 I/O、数据库操作、Web 服务器等多种场景,大大提高应用程序的并发性能和响应速度。

希望本文对你理解和应用 Python asyncio 有所帮助!

以上就是Python asyncio核心原理与高阶应用全解析的详细内容,更多关于Python asyncio的资料请关注脚本之家其它相关文章!

相关文章

  • 用Python实现控制电脑鼠标

    用Python实现控制电脑鼠标

    大家好,本篇文章主要讲的是用Python实现控制电脑鼠标,感兴趣的同学赶快来看一看吧,对你有帮助的话记得收藏一下
    2022-01-01
  • 在Tensorflow中实现梯度下降法更新参数值

    在Tensorflow中实现梯度下降法更新参数值

    今天小编就为大家分享一篇在Tensorflow中实现梯度下降法更新参数值,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2020-01-01
  • Appium Python自动化测试之环境搭建的步骤

    Appium Python自动化测试之环境搭建的步骤

    这篇文章主要介绍了Appium Python自动化测试之环境搭建的步骤,以32位的Windows 7操作系统为例介绍Appium+Python的环境搭建步骤,感兴趣的小伙伴们可以参考一下
    2019-01-01
  • Python学习之异常处理的避坑指南

    Python学习之异常处理的避坑指南

    这篇文章主要介绍了Python中异常处理的一些避坑指南,文中的示例代码讲解详细,对我们学习Python有一定帮助,感兴趣的小伙伴可以学习一下
    2022-03-03
  • Pycharm使用matplotlib警告\不能显示的问题及解决

    Pycharm使用matplotlib警告\不能显示的问题及解决

    在PyCharm中使用matplotlib画图时遇到警告和图像显示问题,通过在代码中添加`mpl.use('TkAgg')`或`plt.switch_backend('TkAgg')`,可以解决警告并弹出显示完整的图像窗口,同时,文章还列举了matplotlib的其他backend选项,如Qt4Agg、Qt5Agg、WXAgg等
    2025-02-02
  • 浅谈python数据结构之动态规划

    浅谈python数据结构之动态规划

    这篇文章主要介绍了浅谈python数据结构之动态规划,可能很多小伙伴会觉得这个词很陌生,觉得这是一种很复杂的思想,学习起来很困难,其实并不是这样,动态规划所讲述的知识与动态与规划并无太大关联,需要的朋友可以参考下
    2023-07-07
  • python中update的基本使用方法详解

    python中update的基本使用方法详解

    这篇文章主要介绍了python中update的基本使用方法详解,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
    2019-07-07
  • flask框架单元测试原理与用法实例分析

    flask框架单元测试原理与用法实例分析

    这篇文章主要介绍了flask框架单元测试原理与用法,结合实例形式较为详细的分析了单元测试的概念、原理及基本用法,需要的朋友可以参考下
    2019-07-07
  • 浅析python连接数据库的重要事项

    浅析python连接数据库的重要事项

    这篇文章主要介绍了python连接数据库的重要事项,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
    2021-02-02
  • python验证码识别教程之灰度处理、二值化、降噪与tesserocr识别

    python验证码识别教程之灰度处理、二值化、降噪与tesserocr识别

    这篇文章主要给大家介绍了关于python验证码识别教程之灰度处理、二值化、降噪与tesserocr识别的相关资料,文中通过示例代码介绍的非常详细,需要的朋友可以参考借鉴,下面随着小编来一起学习学习吧
    2018-06-06

最新评论