【python asyncio模块的协程使用示例】

在这里插入图片描述

asyncio是Python的一个异步I/O框架,允许使用async/await语法进行并发编程。以下是多个使用asyncio的例子:

异步执行的基本示例

import asyncio

async def hello_world():
    print("Hello, World!")

asyncio.run(hello_world())

异步休眠

import asyncio

async def async_sleep(duration):
    print(f"Sleeping for {duration} seconds...")
    await asyncio.sleep(duration)
    print(f"Slept for {duration} seconds")

asyncio.run(async_sleep(3))

异步获取网页内容

import asyncio
import aiohttp

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

url = "https://www.example.com/"
html = asyncio.run(fetch(url))
print(html)

多个异步任务并发执行

import asyncio

async def print_numbers():
    for i in range(10):
        print(i)
        await asyncio.sleep(1)

async def print_letters():
    for letter in 'abcdefghij':
        print(letter)
        await asyncio.sleep(2)

async def main():
    task1 = asyncio.create_task(print_numbers())
    task2 = asyncio.create_task(print_letters())

    await asyncio.gather(task1, task2)

asyncio.run(main())

使用异步队列进行生产者-消费者模式

import asyncio
import random

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

async def consumer(queue):
    while True:
        item = await queue.get()
        if item is None:
            break
        print(f"Consumed {item}")
        await asyncio.sleep(random.random())

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

    await producer_task
    await queue.put(None)
    await consumer_task

asyncio.run(main())

以上示例展示了使用asyncio执行基本的异步任务,异步休眠,获取网页内容,同时执行多个任务和实现生产者-消费者模式。

异步执行多个协程并获取结果

import asyncio

async def square(x):
    await asyncio.sleep(1)
    return x * x

async def main():
    tasks = [square(i) for i in range(5)]
    results = await asyncio.gather(*tasks)
    print(results)

asyncio.run(main())

异步执行有超时限制的任务

pythonCopy codeimport asyncio

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

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

asyncio.run(main())

异步执行周期性任务

pythonCopy codeimport asyncio

async def periodic_task(interval):
    while True:
        print("Periodic task executed")
        await asyncio.sleep(interval)

async def main():
    task = asyncio.create_task(periodic_task(2))
    await asyncio.sleep(10)
    task.cancel()
    try:
        await task
    except asyncio.CancelledError:
        print("Periodic task cancelled")

asyncio.run(main())
  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值