异步编程 - Python中的yield from的用法?
迷茫
迷茫 2017-04-18 10:04:59
[Python讨论组]

对于yield from目前我只知道这一种用法,我对它的理解也停留在yield from generator

In [1]: def reader():
   ...:     """A generator that fakes a read from a file, socket, etc."""
   ...:     for i in range(4):
   ...:         yield '<< %s' % i
   ...:         

In [2]: def reader_wrapper(g):
   ...:     yield from g
   ...:     

In [3]: wrap = reader_wrapper(reader())

In [4]: for i in wrap:
   ...:     print(i)
   ...:     
<< 0
<< 1
<< 2
<< 3

但是在廖雪峰的异步IO教程中看见一个yield from的新用法,请问下面这个yield from asyncio.sleep(1)是什么意思,asyncio.sleep(1)也是一个生成器吗?看官方文档也没有给出明确的解释,也是直接贴的代码,拜托大神解释一下!

import asyncio

@asyncio.coroutine
def hello():
    print("Hello world!")
    # 异步调用asyncio.sleep(1):
    r = yield from asyncio.sleep(1)
    print("Hello again!")

# 获取EventLoop:
loop = asyncio.get_event_loop()
# 执行coroutine
loop.run_until_complete(hello())
loop.close()
迷茫
迷茫

业精于勤,荒于嬉;行成于思,毁于随。

全部回复(3)
PHPz

协程的本质就是是生成器

可以看看这个视频~
探索 Python 3.5 中 async/await 特性的实现

PHPz

为什么要包装一次了?

for i in reader():
    print(i)

这样也能用啊?很纳闷。。。

巴扎黑

可以看看 Python 作者写的这篇文章,糙译

热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送

Copyright 2014-2026 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号