python3 async await(python中使用asyncio实现异步IO)
导读:1、说明...
1 、说明
Python实现异步IO非常简单 ,asyncio是Python 3.4版本引入的标准库 ,直接内置了对异步IO的支持 。
asyncio的编程模型就是一个消息循环 。我们从asyncio模块中直接获取一个EventLoop的引用 ,然后把需要执行的协程扔到EventLoop中执行 ,就实现了异步IO 。
2 、实例
importasyncio @asyncio.coroutine defwget(host): print(wget%s...%host) connect=asyncio.open_connection(host,80) reader,writer=yieldfromconnect header=GET/HTTP/1.0\r\nHost:%s\r\n\r\n%host writer.write(header.encode(utf-8)) yieldfromwriter.drain() whileTrue: line=yieldfromreader.readline() ifline==b\r\n: break print(%sheader>%s%(host,line.decode(utf-8).rstrip())) #Ignorethebody,closethesocket writer.close() loop=asyncio.get_event_loop() tasks=[wget(host)forhostin[www.sina.com.cn,www.sohu.com,www.163.com]] loop.run_until_complete(asyncio.wait(tasks)) loop.close()创心域SEO版权声明:以上内容作者已申请原创保护,未经允许不得转载,侵权必究!授权事宜、对本内容有异议或投诉,敬请联系网站管理员,我们将尽快回复您,谢谢合作!