asyncio
asyncio是python3.4版本引入的标准库,直接内置了对异步IO的支持。
asyncio的编程模型就是一个消息循环。我们从asyncio模块中直接获取一个EventLoop的引用,把需要执行的协程扔到EventLoop中执行,就实现了异步IO.
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:在生成器gen中使用yield from subgen()时,subgen会获得控制权,把产出的值传给gen的调用方(这里为事件循环),即调用方可以控制subgen,与此同时gen会阻塞,等待subgen终止。
yield from可用于简化for循环中的yield表达式,例如:
def gen(): for c in 'AB': yield c for i in range(1, 3): yield i list(gen()) ['A', 'B', '1', '2']
可以改写为:
def gen(): yield from 'AB' yield from range(1, 3) list(gen()) ['A', 'B', '1', '2']
如有疑问请联系我,写的不对的地方请联系我进行更改,感谢~ QQ:1968380831