asyncio
是Python 3.4版本引入的标准库,直接内置了对异步IO的支持。html
asyncio
的编程模型就是一个消息循环。咱们从asyncio
模块中直接获取一个EventLoop
的引用,而后把须要执行的协程扔到EventLoop
中执行,就实现了异步IO。编程
用asyncio
实现Hello world
代码以下:网络
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()
@asyncio.coroutine把一个generator标记为coroutine类型,而后,就把这个coroutine扔到eventloop中去执行并发
hello()会先打印出helloworld,而后yield from能够让咱们方便的调用另外一个generator,因为asyncio.sleep(1)也是一个coroutine异步
因此线程不会等待asyncio.sleep而是直接中断并执行下一个消息循环,当asyncio.sleep返回的时候,线程就在yield from拿到返回值,此处是Nonesocket
而后执行下一个语句async
把asyncio.sleep(1)当作是一个耗时1秒的IO操做。在此期间主线程没有等待,而是去执行eventloop其余能够执行的coroutine所以能够实现并发执行oop
接下来封装2个coroutine试试网站
import threading import asyncio @asyncio.coroutine def hello(): print('Hello world! (%s)' % threading.currentThread()) yield from asyncio.sleep(1) print('Hello again! (%s)' % threading.currentThread()) loop = asyncio.get_event_loop() tasks = [hello(), hello()] loop.run_until_complete(asyncio.wait(tasks)) loop.close()
Hello world! (<_MainThread(MainThread, started 140735195337472)>) Hello world! (<_MainThread(MainThread, started 140735195337472)>) (暂停约1秒) Hello again! (<_MainThread(MainThread, started 140735195337472)>) Hello again! (<_MainThread(MainThread, started 140735195337472)>)
由打印的当前线程名称能够看出,两个coroutine是由同一个线程并发执行的。
若是把asyncio.sleep()换成真正的IO操做,则多个coroutine就能够由一个线程并发执行。
咱们用asyncio的异步网络链接来获取sina、sohu和163的网站首页:
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()
wget www.sohu.com... wget www.sina.com.cn... wget www.163.com... (等待一段时间) (打印出sohu的header) www.sohu.com header > HTTP/1.1 200 OK www.sohu.com header > Content-Type: text/html ... (打印出sina的header) www.sina.com.cn header > HTTP/1.1 200 OK www.sina.com.cn header > Date: Wed, 20 May 2015 04:56:33 GMT ... (打印出163的header) www.163.com header > HTTP/1.0 302 Moved Temporarily www.163.com header > Server: Cdn Cache Server V2.0
asyncio
提供了完善的异步IO支持;spa
异步操做须要在coroutine
中经过yield from
完成;
多个coroutine
能够封装成一组Task而后并发执行。