-
python基础教程之Python3标准库:asyncio异步I/O、事件循环和并发工具(4)
本站最新发布 Python从入门到精通|Python基础教程
试听地址 https://www.xin3721.com/eschool/pythonxin3721/
'
async def main(loop):
print('creating task')
task = loop.create_task(task_func())
print('canceling task')
task.cancel()
print('canceled task {!r}'.format(task))
try:
await task
except asyncio.CancelledError:
print('caught error from canceled task')
else:
print('task result: {!r}'.format(task.result()))
event_loop = asyncio.get_event_loop()
try:
event_loop.run_until_complete(main(event_loop))
finally:
event_loop.close()
试听地址 https://www.xin3721.com/eschool/pythonxin3721/
'
这个例子会在启动事件循环之前创建一个任务,然后取消这个任务。结果是run_unitl_complete()方法抛出一个CancelledError异常。
如果一个任务正在等待另一个并发运行的操作完成,那么倘若在这个等待时刻取消任务,则其会通过此时产生的一个CancelledError异常通知任务将其取消。
- import asyncio
- async def task_func():
- print('in task_func, sleeping')
- try:
- await asyncio.sleep(1)
- except asyncio.CancelledError:
- print('task_func was canceled')
- raise
- return 'the result'
- def task_canceller(t):
- print('in task_canceller')
- t.cancel()
- print('canceled the task')
- async def main(loop):
- print('creating task')
- task = loop.create_task(task_func())
- loop.call_soon(task_canceller, task)
- try:
- await task
- except asyncio.CancelledError:
- print('main() also sees task as canceled')
- event_loop = asyncio.get_event_loop()
- try:
- event_loop.run_until_complete(main(event_loop))
- finally:
- event_loop.close()
捕捉异常会提供一个机会,如果必要,可以利用这个机会清理已经完成的工作。
1.5.3 从协程创建任务
ensure_future()函数返回一个与协程执行绑定的Task。这个Task实例再传递到其他代码,这个代码可以等待这个实例,而无须知道原来的协程是如何构造或调用的。
- import asyncio
- async def wrapped():
- print('wrapped')
- return 'result'
- async def inner(task):
- print('inner: starting')
- print('inner: waiting for {!r}'.format(task))
- result = await task
- print('inner: task returned {!r}'.format(result))
- async def starter():
- print('starter: creating task')
- task = asyncio.ensure_future(wrapped())
- print('starter: waiting for inner')
- await inner(task)
- print('starter: inner returned')
- event_loop = asyncio.get_event_loop()
- try:
- print('entering event loop')
- result = event_loop.run_until_complete(starter())
- finally:
- event_loop.close()
需要说明,对于提供给ensure_future()的协程,在使用await之前这个协程不会启动,只有await才会让它执行。
1.6 组合协程和控制结构
一系列协程之间的线性控制流用内置关键字await可以很容易地管理。更复杂的结构可能允许一个协程等待多个其他协程并行完成,可以使用asyncio中的工具创建这些更复杂的结构。
1.6.1 等待多个协程
通常可以把一个操作划分为多个部分,然后分别执行,这会很有用。例如,采用这种方法,可以高效地下载多个远程资源或者查询远程API。有些情况下,执行顺序并不重要,而且可能有任意多个操作,可以使用wait()暂停一个协程,直到其他后台操作完成。
- import asyncio
- async def phase(i):
- print('in phase {}'.format(i))
- await asyncio.sleep(0.1 * i)
- print('done with phase {}'.format(i))
- return 'phase {} result'.format(i)
栏目列表
最新更新
如何使用OS模块中的stat方法
Python os 模块
seek() 方法
python打开文件实例1
Python写入文件
什么是流?
文件操作如何进制逐行读取
Python相对路径
with创建临时运行环境
Python文件操作
.Net Standard(.Net Core)实现获取配置信息
Linux PXE + Kickstart 自动装机
Shell 编程 基础
Shell 编程 条件语句
CentOS8-网卡配置及详解
Linux中LVM逻辑卷管理
1.数码相框-相框框架分析(1)
Ubuntu armhf 版本国内源
Linux中raid磁盘阵列
搭建简易网站
access教程之Access简介
mysql 安装了最新版本8.x版本后的报错:
Mysql空间数据&空间索引(spatial)
如何远程连接SQL Server数据库的图文教程
复制SqlServer数据库的方法
搜索sql语句
sql中返回参数的值
sql中生成查询的模糊匹配字符串
数据定义功能
数据操作功能