python学习笔记(三十九) -- yield from 、asyncio、async/await 、aiohttp

本文详细介绍了Python中的yield from关键字、asyncio模块、async/await语法以及aiohttp库在异步编程中的应用。通过实例展示了如何利用这些特性实现高效的单线程并发IO操作,从而提高CPU利用率。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Table of Contents

 

前言

yield from

asyncio

async/await 

aiohttp


前言

由于 cpu和 磁盘读写的 效率有很大的差距,往往cpu执行代码,然后遇到需要从磁盘中读写文件的操作,此时主线程会停止运行,等待IO操作完成后再继续进行,这要就导致cpu的利用率非常的低。

协程可以实现单线程同时执行多个任务,但是需要自己手动的通过send函数和yield关键字配合来传递消息,asyncio模块能够自动帮我们传递消息。

在介绍asyncio模块之前我们先来了解一下yield from 关键字


yield from

作用1   包含yield from 关键字的函数也会编程一个generator对象。

作用2   yield from 关键字后面是一个iterable对象,其含义与下面类似

for item in iterable:
    print(item)

看案例

>>> def test1():
	yield [1,2,3,4,5]

	
>>> t1 = test1()
>>> next(t1)
[1, 2, 3, 4, 5]


-----------------------------------------------------------------------------------------

>>> def test1():
	yield from [1,2,3,4,5]

	
>>> t=test1()
>>> next(t)
1
>>> next(t)
2
>>> next(t)
3
>>> next(t)
4
>>> next(t)
5

 

如果yield from 关键字后面是一个generator对象,又因为包含yield from的函数也会变成Iterator对象,所以之后迭代该Iterator对象,实际上迭代的是yield from 后面的Iterator对象,话说起来比较绕

看个简单的案例

>>> def test1():
	a = 0
	while 1:
		a = a+1
		yield a

		
>>> def test2():
	yield from test1()

	
>>> t2=test2()
>>> next(t2)   # 实际迭代的是test1这个generator
1
>>> next(t2)
2
>>> next(t2)
3
>>> next(t2)
4
>>> next(t2)
5

再看一个案例

def htest():
    i = 1
    while i < 4:
        print('i', i)
        n = yield i
        print('n', n)
        if i == 3:
            return 100
        i += 1


def itest():
    val = yield from htest()      
    print(val)


t = itest()
print(type(t))
t.send
### Python 中 `async`、`await` `yield` 关键字详解 #### 1. `async` 定义异步函数 `async` 是用于定义协程的关键字。当一个函数被声明为 `async def` 形式时,它返回的是一个协程对象而不是立即执行的结果。这种设计使得该函数可以包含 `await` 表达式来暂停其自身的执行并等待另一个协程完成。 ```python import asyncio async def my_coroutine(): print("Start") await asyncio.sleep(1) # 模拟耗时操作 print("End") # 运行协程 asyncio.run(my_coroutine()) ``` #### 2. `await` 执行异步调用 `await` 只能在由 `async def` 声明的函数内部使用,用来挂起当前协程直到右侧表达式的协程完成,并获取它的结果。这允许编写看起来像同步代码但实际上是非阻塞的操作序列[^1]。 ```python async def fetch_data(): data = await get_remote_resource() process(data) async def main(): result = await fetch_data() asyncio.run(main()) ``` #### 3. `yield` 实现生成器与旧版协程 `yield` 主要用于创建迭代器(即生成器),但在早期版本中也被用来支持基于生成器的协程语法。通过 `@asyncio.coroutine` 装饰器配合 `yield from` 来模拟现代的 `await` 功能。不过这种方式已经被弃用了,在新项目里应该优先考虑使用更直观易读的新风格——`async/await`[^3]。 ```python from asyncio import coroutine @coroutine def old_style_coro(): value = yield from some_async_operation() handle_result(value) ``` #### 区别总结 - **适用范围**: `async` `await` 组合专为构建高效的并发应用程序而设;相比之下,虽然 `yield` 同样能做些类似的事情但它主要用于数据流处理场景下的惰性求值。 - **语法规则**: 使用 `async` 函数内的任何地方都可以放置 `await` 语句去等待其他协程结束工作;然而只有在特定上下文中才可合法地运用带有 `yield` 的生成器作为简单的协程替代品。 - **性能表现**: 新型 `async/await` 结构不仅简化了编码逻辑而且提高了程序的整体效率,因为它们更好地集成了底层事件循环机制[^4]。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值