Python 的yield在这里的作用是啥?

import asyncio

@asyncio.coroutine
def wget(host):
    print('wget %s...' % host)
    connect = asyncio.open_connection(host, 80)
    reader, writer = yield from connect
    header = 'GET / HTTP/1.0\r\nHost: %s\r\n\r\n' % host
    writer.write(header.encode('utf-8'))
    yield from writer.drain()
    while True:
        line = yield from reader.readline()
        if line == b'\r\n':
            break
        print('%s header > %s' % (host, line.decode('utf-8').rstrip()))
    # Ignore the body, close the socket
    writer.close()

loop = asyncio.get_event_loop()
tasks = [wget(host) for host in ['www.sina.com.cn', 'www.sohu.com', 'www.163.com']]
loop.run_until_complete(asyncio.wait(tasks))
loop.close()

请问在这里的`
yield from writer.drain()

和```
line = yield from reader.readline()

里的yield有什么作用

阅读 3.8k
2 个回答

yield from iterable本质上等于for item in iterable: yield item的缩写版

yield 是迭代器,相比 for...in 来说只读取一次,这里用于循环读写和刷新缓冲区,尤其是读取写入大量数据而内存不够的时候很有用,想象一下写一下刷一下,接着写一下刷一下...
省内存啊...
抛砖引玉了...

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题