脚本之家,脚本语言编程技术及教程分享平台!
分类导航

Python|VBS|Ruby|Lua|perl|VBA|Golang|PowerShell|Erlang|autoit|Dos|bat|shell|

服务器之家 - 脚本之家 - Python - 我们一起聊聊Python协程和异步编程

我们一起聊聊Python协程和异步编程

2023-11-29 16:35测试开发学习交流 Python

协程和异步编程是Python中处理并发和异步任务的重要概念。协程是一种轻量级的并发编程方式,它允许程序在执行过程中暂停和恢复,以便处理其他任务。

协程和异步编程是Python中处理并发和异步任务的重要概念。协程是一种轻量级的并发编程方式,它允许程序在执行过程中暂停和恢复,以便处理其他任务。异步编程模型则是基于协程的一种编程风格,它通过使用非阻塞的异步IO操作来提高程序的并发性能。

Python中的异步编程主要依赖于`asyncio`模块。`asyncio`提供了一套用于编写异步代码的工具和框架,包括协程、事件循环和异步IO操作等。

代码示例:

1. 使用`async`和`await`定义协程函数:

import asyncio


async def my_coroutine():
    await asyncio.sleep(1)
    print("Coroutine executed")


asyncio.run(my_coroutine())

2. 使用`asyncio.create_task()`并发运行多个协程:

import asyncio


async def coroutine1():
    await asyncio.sleep(1)
    print("Coroutine 1 executed")


async def coroutine2():
    await asyncio.sleep(2)
    print("Coroutine 2 executed")


async def main():
    task1 = asyncio.create_task(coroutine1())
    task2 = asyncio.create_task(coroutine2())
    await asyncio.gather(task1, task2)


asyncio.run(main())

3. 使用`asyncio.wait()`等待多个协程完成:

import asyncio


async def coroutine1():
    await asyncio.sleep(1)
    print("Coroutine 1 executed")


async def coroutine2():
    await asyncio.sleep(2)
    print("Coroutine 2 executed")


async def main():
    tasks = [coroutine1(), coroutine2()]
    done, pending = await asyncio.wait(tasks)
    for task in done:
        print(f"Task {task} completed")


asyncio.run(main())

4. 使用`asyncio.Lock()`实现协程间的互斥访问:

import asyncio


async def counter(lock):
    async with lock:
        for _ in range(5):
            print("Counting")
            await asyncio.sleep(1)


async def main():
    lock = asyncio.Lock()
    tasks = [counter(lock) for _ in range(3)]
    await asyncio.gather(*tasks)


asyncio.run(main())

5. 使用`asyncio.Queue()`实现协程间的消息传递:

import asyncio


async def producer(queue):
    for i in range(5):
        await queue.put(i)
        print(f"Produced: {i}")
        await asyncio.sleep(1)


async def consumer(queue):
    while True:
        item = await queue.get()
        print(f"Consumed: {item}")
        await asyncio.sleep(2)


async def main():
    queue = asyncio.Queue()
    producer_task = asyncio.create_task(producer(queue))
    consumer_task = asyncio.create_task(consumer(queue))
    await asyncio.gather(producer_task, consumer_task)


asyncio.run(main())

6. 使用`asyncio.TimeoutError`设置协程的超时:

import asyncio


async def my_coroutine():
    await asyncio.sleep(2)
    print("Coroutine executed")


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


asyncio.run(main())

7. 使用`asyncio.run_in_executor()`在协程中执行阻塞的同步操作:

import asyncio


def sync_operation():
    # 阻塞的同步操作
    return "Sync result"


async def main():
    loop = asyncio.get_running_loop()
    result = await loop.run_in_executor(None, sync_operation)
    print(f"Result: {result}")


asyncio.run(main())

8. 使用`aiohttp`库进行异步HTTP请求:

import asyncio
import aiohttp


async def fetch_data(url):
    async with aiohttp.ClientSession() as session:
        async with session.get(url) as response:
            return await response.text()


async def main():
    url = "https://api.example.com/data"
    data = await fetch_data(url)
    print(f"Data: {data}")


asyncio.run(main())

9. 使用`asyncio.sleep()`模拟异步计时器:

import asyncio


async def timer(duration):
    await asyncio.sleep(duration)
    print(f"Timer finished after {duration} seconds")


async def main():
    tasks = [timer(1), timer(2), timer(3)]
    await asyncio.gather(*tasks)


asyncio.run(main())

10. 使用`asyncio`实现并发的文件IO操作:

import asyncio


async def read_file(file):
    async with asyncio.open_file(file, "r") as f:
        contents = await f.read()
        print(f"Read from {file}: {contents}")


async def write_file(file, data):
    async with asyncio.open_file(file, "w") as f:
        await f.write(data)
        print(f"Wrote to {file}")


async def main():
    file = "data.txt"
    await write_file(file, "Hello, world!")
    await read_file(file)


asyncio.run(main())

这些场景代码展示了协程和异步编程的使用方式。通过使用`asyncio`模块和相关的工具,我们可以轻松地编写并发和异步任务处理的代码,提高程序的性能和响应能力。

原文地址:https://mp.weixin.qq.com/s/1AafcbnpKoUM2LOrImgH5w

延伸 · 阅读

精彩推荐
  • Python仅用500行Python代码实现一个英文解析器的教程

    仅用500行Python代码实现一个英文解析器的教程

    这篇文章主要介绍了仅用500行Python代码实现一个英文解析器的教程,自然语言处理近来也是业界中一个热门课题,作者为NLP方向的开发者,需要的朋友可以参考...

    Matthew Honnibal2072020-05-28
  • Python如何处理Python3.4 使用pymssql 乱码问题

    如何处理Python3.4 使用pymssql 乱码问题

    这篇文章主要介绍了如何处理Python3.4 使用pymssql 乱码问题的相关资料,涉及到python pymssql相关知识,对此感兴趣的朋友一起学习吧 ...

    firecrow7512020-08-06
  • Python如何优雅地改进Django中的模板碎片缓存详解

    如何优雅地改进Django中的模板碎片缓存详解

    这篇文章主要给大家介绍了关于如何优雅地改进Django中的模板碎片缓存的相关资料,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的...

    栖迟于一丘10912021-03-13
  • Pythonpython 将json数据提取转化为txt的方法

    python 将json数据提取转化为txt的方法

    今天小编就为大家分享一篇python 将json数据提取转化为txt的方法,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧...

    sxf_012312212021-04-13
  • PythonOpenCV 图像绘制的实现

    OpenCV 图像绘制的实现

    本文主要介绍了OpenCV 图像绘制的实现,主要包括直线,圆,多边形和自定义图形等,具有一定的参考价值,感兴趣的可以了解一下...

    琉璃灯的眷恋11572021-12-13
  • PythonPython模拟登陆实现代码

    Python模拟登陆实现代码

    本篇文章主要介绍了Python模拟登陆实现代码,这里整理了详细的代码,具有一定的参考价值,感兴趣的小伙伴们可以参考一下...

    薛定谔的-狗3982020-11-18
  • Python用python 批量操作redis数据库

    用python 批量操作redis数据库

    这篇文章主要介绍了如何用python 批量操作redis数据库,帮助大家更好的理解和学习使用python,感兴趣的朋友可以了解下...

    binger07125822021-09-18
  • Python实例讲解Python中函数的调用与定义

    实例讲解Python中函数的调用与定义

    这篇文章主要介绍了Python中函数的调用与定义,是Python入门学习中的基础知识,需要的朋友可以参考下...

    YoferZhang3882020-08-16