需要了解协程的请参考:
目录
1. 事件循环
理解成为一个死循环,去检测并执行某些代码。
# 伪代码
任务列表 = [任务1。任务2,任务3,...l
while True:
可执行的任务列表,已完成的任务列表 = 去任务列表中检查所有的任务,将"可执行"和"已完成"的任务返回
for 就绪任务 in 可执行的任务列表:
执行已就绪的任务
for 已完成的任务 in 已完成的任务列表:
在任务列表中移除已完成的任务
如果任务列表中的任务都已完成,则终止循环
import asyncio
async def func1():
print(1)
await asyncio.sleep(2) # 遇到IO耗时操作自动切换到tasks中的其它任务
print(2)
async def func2():
print(3)
await asyncio.sleep(2)
print(4)
tasks = [
asyncio.ensure_future( func1() ),
asyncio.ensure_future( func2() ),
]
loop = asyncio.get_event_loop() # 生成或获取一个事件循环
loop.run_until_complete(asyncio.wait(tasks)) # 将任务放到任务列表
2. 快速上手
协程函数:async def 函数名
协程对象:执行协程函数得到的对象
例如:
# 协程函数
async def func():
pass
# 协程对象
result = func()
注意:执行协程函数创建的协程对象,函数内部代码不会执行。
可通过如下代码执行:
import asyncio
async def func():
print("test")
result = func()
loop = asyncio.get_event_loop()
loop.run_until_complete( result )
python 3.7版本及以上可用如下代码实现:
import asyncio
async def func():
print("test")
result = func()
asyncio.run( result )
3. await
await就是等待对象的值得到结果之后再继续向下执行
用法:await + 可等待的对象
可等待的对象有:协程对象、Future对象、Task对象
示例1:
import asyncio
async def func():
print("test")
response = await asyncio.sleep(2) # 这里用asyncio.sleep(2)来模拟一个网络请求操作
print("结束",response)
asyncio.run(func())
示例2:
import asyncio
async def others():
print("start")
await asyncio.sleep(2)
print("end")
return "返回值"
async def func():
print("执行协程函数内部代码")
response = await others()
print("IO请求结束,结果为:",response)
asyncio.run(func())
结果:
示例3:
import asyncio
async def others():
print("start")
await asyncio.sleep(2)
print("end")
return "返回值"
async def func():
print("执行协程函数内部代码")
response1 = await others()
print("IO请求结束,结果为:",response1)
response2 = await others()
print("IO请求结束,结果为:", response2)
asyncio.run(func())
结果:
4. Task对象
就是在事件循环中用来添加多个任务的。
Tasks用于并发调度协程,通过asyncio.create_task(协程对象)的方式创建Task对象,这样可以让协程加入事件循环中等待被调度执行。除了使用asyncio.create_task()函数以外,还可以用低层级的loop.create_task()或ensure_future()函数。不建议手动实例化Task对象。
注意:asyncio.create_task()函数在Python 3.7中被加入。在Python 3.7之前,可以改用低层级的asyncio.ensure_future()函数。
示例:
import asyncio
async def func():
print("1")
await asyncio.sleep(2)
print("2")
return "返回值"
async def main():
print("main开始")
task1 = asyncio.create_task(func())
task2 = asyncio.create_task(func())
print("main结束")
# 当执行某协程遇到IO操作时,会自动化切换执行其他任务。
# 此处的await是等待相对应的协程全都执行完毕并获取结果
ret1 = await task1
ret2 = await task2
print(ret1,ret2)
asyncio.run(main())
结果:
将以上代码换一种写法,如下:
import asyncio
async def func():
print("1")
await asyncio.sleep(2)
print("2")
return "返回值"
async def main():
print("main开始")
task_list = [
asyncio.create_task(func()),
asyncio.create_task(func()),
]
print("main结束")
done,pending = await asyncio.wait(task_list, timeout=2) #timeout表示只等2s,超过2s就不等了
print(done,pending)
asyncio.run(main())
5. asyncio.Future对象
Task继承Future,Task对象内部await结果的处理基于Future对象来的。
示例1:
import asyncio
async def main():
# 获取当前事件循环
loop = asyncio.get_running_loop()
# 创建一个任务(Future对象),这个任务什么都不干
fut = loop.create_future()
# 等待任务最终结果(Future对象),没有结果则会一直等待下去
await fut
asyncio.run( main())
示例2:
import asyncio
async def set_after(fut):
await asyncio.sleep(2)
fut.set_result("666")
async def main():
# 获取当前事件循环
loop = asyncio.get_running_loop()
# 创建一个任务(Future对象),这个任务什么都不干
fut = loop.create_future()
# 创建一个任务(Task对象),绑定了set_after函数,函数内部在2s之后,会给fut赋值。
# 即手动设置future任务的最终结果,那么fut就可以结束了。
await loop.create_task(set_after(fut))
# 等待任务最终结果(Future对象),没有结果则会一直等待下去
data = await fut
print(data)
asyncio.run( main())
6. 异步迭代器
什么是异步迭代器?
实现了__aiter__()和__anext__()方法的对象。__anext__必须返回一个awaitable对象。async_for 会处理异步迭代器的__anext__()方法所返回的可等待对象,直到其引发一个StopAsyncIteration 异常。
什么是异步可迭代对象?
可在 async for语句中被使用的对象。必须通过它的__aiter__()方法返回一个 asynchronous iterator。
示例:
import asyncio
class Reader(object):
"""自定义异步迭代器(同时也是异步可迭代对象)"""
def __init__(self):
self.count = 0
async def readline(self):
# await asyncio.sleep(1)
self.count += 1
if self.count == 100:
return None
return self.count
def __aiter__(self):
return self
async def __anext__(self):
val = await self.readline()
if val == None:
raise StopAsyncIteration
return val
if __name__ == '__main__':
async def main():
obj = Reader()
async for item in obj:
print(item)
asyncio.run(main())