当前位置: 移动技术网 > IT编程>脚本编程>Python > Python中asyncio模块的深入讲解

Python中asyncio模块的深入讲解

2019年07月21日  | 移动技术网IT编程  | 我要评论

渝是哪个省,汽车桥壳,死神之八云六道

1. 概述

python中 asyncio 模块内置了对异步io的支持,用于处理异步io;是python 3.4版本引入的标准库。

asyncio 的编程模型就是一个消息循环。我们从 asyncio 块中直接获取一个 eventloop 的引用,然后把需要执行的协程扔到 eventloop 中执行,就实现了异步io。

2. 用asyncio实现hello world

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# @time : 2019/1/9 11:23
# @author : arrow and bullet
# @filename: test.py
# @software: pycharm
# @blog :https://blog.csdn.net/qq_41800366
import asyncio

@asyncio.coroutine
def hello():
 print("hello world!")
 # 异步调用asyncio.sleep(2): 
 yield from asyncio.sleep(2)
 print("hello again!")

# 获取eventloop:
loop = asyncio.get_event_loop()
# 执行coroutine
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(2)看成是一个耗时2秒的io操作(比如读取大文件),在此期间,主线程并未等待,而是去执行 eventloop 中其他可以执行的 coroutine 了,因此可以实现并发执行。

我们用task封装两个coroutine试试:

import threading
import asyncio


@asyncio.coroutine
def hello():
 print('hello world! (%s)' % threading.currentthread())
 yield from asyncio.sleep(2)
 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)>)
(暂停约2秒)
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 ...
wget ...
wget ...
(等待一段时间)
(打印出sohu的header)
header > http/1.1 200 ok
header > content-type: text/html
...
(打印出sina的header)
header > http/1.1 200 ok
header > date: wed, 20 may 2015 04:56:33 gmt
...
(打印出163的header)
header > http/1.0 302 moved temporarily
header > server: cdn cache server v2.0
...

可见3个连接由一个线程通过coroutine并发完成。

3. 小结

asyncio提供了完善的异步io支持;

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

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

好了,以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,谢谢大家对移动技术网的支持。

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网