Python中asyncio模块的深入讲解
1.概述
Python中asyncio模块内置了对异步IO的支持,用于处理异步IO;是Python3.4版本引入的标准库。
asyncio的编程模型就是一个消息循环。我们从asyncio块中直接获取一个EventLoop的引用,然后把需要执行的协程扔到EventLoop中执行,就实现了异步IO。
2.用asyncio实现Helloworld
#!/usr/bin/envpython3
#-*-coding:utf-8-*-
#@Time:2019/1/911:23
#@Author:ArrowandBullet
#@FileName:test.py
#@Software:PyCharm
#@Blog:https://blog.csdn.net/qq_41800366
importasyncio
@asyncio.coroutine
defhello():
print("Helloworld!")
#异步调用asyncio.sleep(2):
yieldfromasyncio.sleep(2)
print("Helloagain!")
#获取EventLoop:
loop=asyncio.get_event_loop()
#执行coroutine
loop.run_until_complete(hello())
loop.close()
@asyncio.coroutine把一个generator标记为coroutine类型,然后,我们就把这个coroutine扔到EventLoop中执行。
hello()会首先打印出Helloworld!,然后,yieldfrom语法可以让我们方便地调用另一个generator。由于asyncio.sleep()也是一个coroutine,所以线程不会等待asyncio.sleep(),而是直接中断并执行下一个消息循环。当asyncio.sleep()返回时,线程就可以从yieldfrom拿到返回值(此处是None),然后接着执行下一行语句。
把asyncio.sleep(2)看成是一个耗时2秒的IO操作(比如读取大文件),在此期间,主线程并未等待,而是去执行EventLoop中其他可以执行的coroutine了,因此可以实现并发执行。
我们用task封装两个coroutine试试:
importthreading
importasyncio
@asyncio.coroutine
defhello():
print('Helloworld!(%s)'%threading.currentThread())
yieldfromasyncio.sleep(2)
print('Helloagain!(%s)'%threading.currentThread())
loop=asyncio.get_event_loop()
tasks=[hello(),hello()]
loop.run_until_complete(asyncio.wait(tasks))
loop.close()
观察执行过程:
Helloworld!(<_MainThread(MainThread,started140735195337472)>)
Helloworld!(<_MainThread(MainThread,started140735195337472)>)
(暂停约2秒)
Helloagain!(<_MainThread(MainThread,started140735195337472)>)
Helloagain!(<_MainThread(MainThread,started140735195337472)>)
由打印的当前线程名称可以看出,两个coroutine是由同一个线程并发执行的。
如果把asyncio.sleep()换成真正的IO操作,则多个coroutine就可以由一个线程并发执行。
我们用asyncio的异步网络连接来获取sina、sohu和163的网站首页:
importasyncio
@asyncio.coroutine
defwget(host):
print('wget%s...'%host)
connect=asyncio.open_connection(host,80)#创建连接
reader,writer=yieldfromconnect
header='GET/HTTP/1.0\r\nHost:%s\r\n\r\n'%host
writer.write(header.encode('utf-8'))
yieldfromwriter.drain()
whileTrue:
line=yieldfromreader.readline()
ifline==b'\r\n':
break
print('%sheader>%s'%(host,line.decode('utf-8').rstrip()))
#Ignorethebody,closethesocket
writer.close()
loop=asyncio.get_event_loop()
tasks=[wget(host)forhostin['www.sina.com.cn','www.sohu.com','www.163.com']]
loop.run_until_complete(asyncio.wait(tasks))
loop.close()
执行结果如下:
wgetwww.sohu.com...
wgetwww.sina.com.cn...
wgetwww.163.com...
(等待一段时间)
(打印出sohu的header)
www.sohu.comheader>HTTP/1.1200OK
www.sohu.comheader>Content-Type:text/html
...
(打印出sina的header)
www.sina.com.cnheader>HTTP/1.1200OK
www.sina.com.cnheader>Date:Wed,20May201504:56:33GMT
...
(打印出163的header)
www.163.comheader>HTTP/1.0302MovedTemporarily
www.163.comheader>Server:CdnCacheServerV2.0
...
可见3个连接由一个线程通过coroutine并发完成。
3.小结
asyncio提供了完善的异步IO支持;
异步操作需要在coroutine中通过yieldfrom完成;
多个coroutine可以封装成一组Task然后并发执行。
好了,以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,谢谢大家对毛票票的支持。