asyncio是Python 3.4版本引入的标准库,直接内置了对异步IO的支持。

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拿到返回值,此处是None

然后执行下一个语句

把asyncio.sleep(1)看成是一个耗时1秒的IO操作。在此期间主线程没有等待,而是去执行eventloop其他可以执行的coroutine因此可以实现并发执行

接下来封装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支持;

异步操作需要在coroutine中通过yield from完成;

多个coroutine可以封装成一组Task然后并发执行。

python学习笔记 异步asyncio的更多相关文章

  1. 【目录】Python学习笔记

    目录:Python学习笔记 目标:坚持每天学习,每周一篇博文 1. Python学习笔记 - day1 - 概述及安装 2.Python学习笔记 - day2 - PyCharm的基本使用 3.Pyt ...

  2. python学习笔记整理——字典

    python学习笔记整理 数据结构--字典 无序的 {键:值} 对集合 用于查询的方法 len(d) Return the number of items in the dictionary d. 返 ...

  3. VS2013中Python学习笔记[Django Web的第一个网页]

    前言 前面我简单介绍了Python的Hello World.看到有人问我搞搞Python的Web,一时兴起,就来试试看. 第一篇 VS2013中Python学习笔记[环境搭建] 简单介绍Python环 ...

  4. python学习笔记之module && package

    个人总结: import module,module就是文件名,导入那个python文件 import package,package就是一个文件夹,导入的文件夹下有一个__init__.py的文件, ...

  5. python学习笔记(六)文件夹遍历,异常处理

    python学习笔记(六) 文件夹遍历 1.递归遍历 import os allfile = [] def dirList(path): filelist = os.listdir(path) for ...

  6. python学习笔记--Django入门四 管理站点--二

    接上一节  python学习笔记--Django入门四 管理站点 设置字段可选 编辑Book模块在email字段上加上blank=True,指定email字段为可选,代码如下: class Autho ...

  7. python学习笔记--Django入门0 安装dangjo

    经过这几天的折腾,经历了Django的各种报错,翻译的内容虽然不错,但是与实际的版本有差别,会出现各种奇葩的错误.现在终于找到了解决方法:查看英文原版内容:http://djangobook.com/ ...

  8. python学习笔记(一)元组,序列,字典

    python学习笔记(一)元组,序列,字典

  9. Pythoner | 你像从前一样的Python学习笔记

    Pythoner | 你像从前一样的Python学习笔记 Pythoner

随机推荐

  1. 数据库学习(三) sql语句中添加函数 to_char,round,连接符||

    ** to char 是把日期或数字转换为字符串  to date 是把字符串转换为数据库中得日期类型  参考资料:https://www.cnblogs.com/hllnj2008/p/533296 ...

  2. 第二十三篇 logging模块(******)

    日志非常重要,而且非常常用,可以通过logging模块实现. 热身运动 import logging logging.debug("debug message") logging. ...

  3. 九度OJ--Q1473

    import java.util.ArrayList;import java.util.Scanner; /* * 题目描述: * 大家都知道,数据在计算机里中存储是以二进制的形式存储的. * 有一天 ...

  4. HDU 1693 Eat the Trees(插头DP,入门题)

    Problem Description Most of us know that in the game called DotA(Defense of the Ancient), Pudge is a ...

  5. PostgreSQL 建库建表脚本

    1.创建角色(create_role.sql) drop role if exists "kq_acs";create role "kq_acs" login ...

  6. tomcat中配置JNDI方法

    1.项目中spring的数据源配置: <bean id="dataSource" class="org.springframework.jndi.JndiObjec ...

  7. Spring Boot(一)入门篇

    SpringBoot概述 Spring Boot的诞生简化了Spring应用开发,SpringBoot提供对Spring容器.第三方插件等很多服务的管理.对于大部分Spring应用,无论是简单的web ...

  8. 微信小程序小程序使用scroll-view不能使用下拉刷新的解决办法

    <scroll-view class="movie-grid-container" scroll-y="true" scroll-x="fals ...

  9. vue2.0中vue-router使用总结

    #在vue-cli所创建的项目中使用 进入到项目的目录后使用  npm install vue-router --save  安装vue-router,同时保存在webpack.Json配置文件中,然 ...

  10. struts2 下载文件

    作者:禅楼望月 当下载的文件名字中不含有汉字,或者下载的文件不需要考虑用户的权限问题时.直接让超链接的href属性为所要下载的文件名即可.否则最好使用struts2的文件下载机制. 以下载图片为例 完 ...