Python 18.2 asyncio
2016-02-18 11:54
513 查看
asyncio
asyncio是python3.4版本引入的标准库,直接内置了对异步IO的支持。
asyncio的编程模型就是一个消息循环。我们从asyncio模块中直接获取一个EventLoop的引用,然后把需要执行的协程扔到EventLoop中执行,就实现了异步IO。
用asyncio实现HelloWorld的代码如下:
import asyncio
@asyncio.coroutine
def hello():
print('Hello,World!')
r = yield from asyncio.sleep(1)
print('Hello,again')
loop =asyncio.get_event_loop()
loop.run_until_complete(hello())
loop.close()
@asyncio.coroutine把一个generator标记为coroutine类型,然后我们就把这个coroutine扔到EventLoop中执行。
hello()会首先打印出Hello,World!然后,yield from语法可以方便的让我们调用另一个generator。由于asyncio.sleep()也是一个coroutine,所以线程不会等待asyncio.sleep(),而是直接中断并执行下一个消息循环。当asyncio.sleep()返回时,线程就可以从yield from拿到返回值(此处是None),然后接着执行下一个语句。
把asyncio.sleep()看作是一个耗时1s的IO操作,在此期间,主线程并未等待,而是去执行EventLoop中其他可执行的coroutine了。因此可以实现并发执行。
我们用Task装两个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()
如果把asyncio.sleep()换成真正的IO操作,则多个coroutine就可以由一个线程并发执行。
我们用sayncio的异步网络连接来获取sina、搜狐、和163的网站首页:
小结:
asyncio提供了完善的异步IO支持。
异步操作需要在coroutine中通过yield from完成。
多个coroutine可以封装成一组Task然后并发执行。
asyncio是python3.4版本引入的标准库,直接内置了对异步IO的支持。
asyncio的编程模型就是一个消息循环。我们从asyncio模块中直接获取一个EventLoop的引用,然后把需要执行的协程扔到EventLoop中执行,就实现了异步IO。
用asyncio实现HelloWorld的代码如下:
import asyncio
@asyncio.coroutine
def hello():
print('Hello,World!')
r = yield from asyncio.sleep(1)
print('Hello,again')
loop =asyncio.get_event_loop()
loop.run_until_complete(hello())
loop.close()
@asyncio.coroutine把一个generator标记为coroutine类型,然后我们就把这个coroutine扔到EventLoop中执行。
hello()会首先打印出Hello,World!然后,yield from语法可以方便的让我们调用另一个generator。由于asyncio.sleep()也是一个coroutine,所以线程不会等待asyncio.sleep(),而是直接中断并执行下一个消息循环。当asyncio.sleep()返回时,线程就可以从yield from拿到返回值(此处是None),然后接着执行下一个语句。
把asyncio.sleep()看作是一个耗时1s的IO操作,在此期间,主线程并未等待,而是去执行EventLoop中其他可执行的coroutine了。因此可以实现并发执行。
我们用Task装两个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就可以由一个线程并发执行。
我们用sayncio的异步网络连接来获取sina、搜狐、和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 ...可见3个连接由一个线程通过coroutine并发完成。
小结:
asyncio提供了完善的异步IO支持。
异步操作需要在coroutine中通过yield from完成。
多个coroutine可以封装成一组Task然后并发执行。
相关文章推荐
- Python动态类型的学习---引用的理解
- Python3写爬虫(四)多线程实现数据爬取
- 垃圾邮件过滤器 python简单实现
- 下载并遍历 names.txt 文件,输出长度最长的回文人名。
- install and upgrade scrapy
- Scrapy的架构介绍
- Centos6 编译安装Python
- 使用Python生成Excel格式的图片
- 让Python文件也可以当bat文件运行
- [Python]推算数独
- Python中zip()函数用法举例
- Python中map()函数浅析
- Python将excel导入到mysql中
- Python在CAM软件Genesis2000中的应用
- 使用Shiboken为C++和Qt库创建Python绑定
- FREEBASIC 编译可被python调用的dll函数示例
- Python 七步捉虫法