python中使用asyncio实现异步IO
发布时间:2024-08-27 14:03:19

1、说明
Python实现异步IO非常简单,asyncio是Python 3.4版本引入的标准库直接内置了对异步IO的支持。
asyncio的编程模型是一个新闻循环。我们直接从asyncio模块中获得Eventloop的引用,然后将要执行的协程扔进Eventlop中执行,实现异步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()以上是Python中使用asyncio实现异步IO的方法,希望对大家有所帮助。更多Python学习指导:python基础教程
下一篇 python协程的两大优势
