目录

1. 简介2. Python历史3. 安装Python3.1. Python解释器4. 第一个Python程序4.1. 使用文本编辑器4.2. 输入和输出5. Python基础5.1. 数据类型和变量5.2. 字符串和编码5.3. 使用list和tuple5.4. 条件判断5.5. 模式匹配5.6. 循环5.7. 使用dict和set6. 函数6.1. 调用函数6.2. 定义函数6.3. 函数的参数6.4. 递归函数7. 高级特性7.1. 切片7.2. 迭代7.3. 列表生成式7.4. 生成器7.5. 迭代器8. 函数式编程8.1. 高阶函数8.1.1. map/reduce8.1.2. filter8.1.3. sorted8.2. 返回函数8.3. 匿名函数8.4. 装饰器8.5. 偏函数9. 模块9.1. 使用模块9.2. 安装第三方模块10. 面向对象编程10.1. 类和实例10.2. 访问限制10.3. 继承和多态10.4. 获取对象信息10.5. 实例属性和类属性11. 面向对象高级编程11.1. 使用__slots__11.2. 使用@property11.3. 多重继承11.4. 定制类11.5. 使用枚举类11.6. 使用元类12. 错误、调试和测试12.1. 错误处理12.2. 调试12.3. 单元测试12.4. 文档测试13. IO编程13.1. 文件读写13.2. StringIO和BytesIO13.3. 操作文件和目录13.4. 序列化14. 进程和线程14.1. 多进程14.2. 多线程14.3. ThreadLocal14.4. 进程 vs. 线程14.5. 分布式进程15. 正则表达式16. 常用内建模块16.1. datetime16.2. collections16.3. argparse16.4. base6416.5. struct16.6. hashlib16.7. hmac16.8. itertools16.9. contextlib16.10. urllib16.11. XML16.12. HTMLParser16.13. venv17. 常用第三方模块17.1. Pillow17.2. requests17.3. chardet17.4. psutil18. 图形界面18.1. 海龟绘图19. 网络编程19.1. TCP/IP简介19.2. TCP编程19.3. UDP编程20. 电子邮件20.1. SMTP发送邮件20.2. POP3收取邮件21. 访问数据库21.1. 使用SQLite21.2. 使用MySQL21.3. 使用SQLAlchemy22. Web开发22.1. HTTP协议简介22.2. HTML简介22.3. WSGI接口22.4. 使用Web框架22.5. 使用模板23. 异步IO23.1. 协程23.2. 使用asyncio23.3. 使用aiohttp24. FAQ25. 期末总结

23.2. 使用asyncio

asyncio的编程模型就是一个消息循环。asyncio模块内部实现了EventLoop,把需要执行的协程扔到EventLoop中执行,就实现了异步IO。

asyncio提供的@asyncio.coroutine可以把一个generator标记为coroutine类型,然后在coroutine内部用yield from调用另一个coroutine实现异步操作。

为了简化并更好地标识异步IO,从Python 3.5开始引入了新的语法asyncawait,可以让coroutine的代码更简洁易读。

asyncio实现Hello world代码如下:

import asyncio

async def hello():
    print("Hello world!")
    # 异步调用asyncio.sleep(1):
    await asyncio.sleep(1)
    print("Hello again!")

asyncio.run(hello())

async把一个函数变成coroutine类型,然后,我们就把这个async函数扔到asyncio.run()中执行。执行结果如下:

Hello!
(等待约1秒)
Hello again!

hello()会首先打印出Hello world!,然后,await语法可以让我们方便地调用另一个async函数。由于asyncio.sleep()也是一个async函数,所以线程不会等待asyncio.sleep(),而是直接中断并执行下一个消息循环。当asyncio.sleep()返回时,就接着执行下一行语句。

asyncio.sleep(1)看成是一个耗时1秒的IO操作,在此期间,主线程并未等待,而是去执行EventLoop中其他可以执行的async函数了,因此可以实现并发执行。

上述hello()还没有看出并发执行的特点,我们改写一下,让两个hello()同时并发执行:

# 传入name参数:
async def hello(name):
    # 打印name和当前线程:
    print("Hello %s! (%s)" % (name, threading.current_thread))
    # 异步调用asyncio.sleep(1):
    await asyncio.sleep(1)
    print("Hello %s again! (%s)" % (name, threading.current_thread))
    return name

asyncio.gather()同时调度多个async函数:

async def main():
    L = await asyncio.gather(hello("Bob"), hello("Alice"))
    print(L)

asyncio.run(main())

执行结果如下:

Hello Bob! (<function current_thread at 0x10387d260>)
Hello Alice! (<function current_thread at 0x10387d260>)
(等待约1秒)
Hello Bob again! (<function current_thread at 0x10387d260>)
Hello Alice again! (<function current_thread at 0x10387d260>)
['Bob', 'Alice']

从结果可知,用asyncio.run()执行async函数,所有函数均由同一个线程执行。两个hello()是并发执行的,并且可以拿到async函数执行的结果(即return的返回值)。

如果把asyncio.sleep()换成真正的IO操作,则多个并发的IO操作实际上可以由一个线程并发执行。

我们用asyncio的异步网络连接来获取sina、sohu和163的网站首页:

import asyncio

async def wget(host):
    print(f"wget {host}...")
    # 连接80端口:
    reader, writer = await asyncio.open_connection(host, 80)
    # 发送HTTP请求:
    header = f"GET / HTTP/1.0\r\nHost: {host}\r\n\r\n"
    writer.write(header.encode("utf-8"))
    await writer.drain()

    # 读取HTTP响应:
    while True:
        line = await 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()
    await writer.wait_closed()
    print(f"Done {host}.")

async def main():
    await asyncio.gather(wget("www.sina.com.cn"), wget("www.sohu.com"), wget("www.163.com"))

asyncio.run(main())

执行结果如下:

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个连接由一个线程并发执行3个async函数完成。

小结

asyncio提供了完善的异步IO支持,用asyncio.run()调度一个coroutine

在一个async函数内部,通过await可以调用另一个async函数,这个调用看起来是串行执行的,但实际上是由asyncio内部的消息循环控制;

在一个async函数内部,通过await asyncio.gather()可以并发执行若干个async函数。

参考源码

hello.py

gather.py

wget.py