VB.net 2010 视频教程 VB.net 2010 视频教程 python基础视频教程
SQL Server 2008 视频教程 c#入门经典教程 Visual Basic从门到精通视频教程
当前位置:
首页 > 编程开发 > python教程 >
  • 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()
  • 这个例子会在启动事件循环之前创建一个任务,然后取消这个任务。结果是run_unitl_complete()方法抛出一个CancelledError异常。

    如果一个任务正在等待另一个并发运行的操作完成,那么倘若在这个等待时刻取消任务,则其会通过此时产生的一个CancelledError异常通知任务将其取消。

    
    
    1. import asyncio
    2.  
    3. async def task_func():
    4. print('in task_func, sleeping')
    5. try:
    6. await asyncio.sleep(1)
    7. except asyncio.CancelledError:
    8. print('task_func was canceled')
    9. raise
    10. return 'the result'
    11.  
    12. def task_canceller(t):
    13. print('in task_canceller')
    14. t.cancel()
    15. print('canceled the task')
    16.  
    17. async def main(loop):
    18. print('creating task')
    19. task = loop.create_task(task_func())
    20. loop.call_soon(task_canceller, task)
    21. try:
    22. await task
    23. except asyncio.CancelledError:
    24. print('main() also sees task as canceled')
    25.  
    26. event_loop = asyncio.get_event_loop()
    27. try:
    28. event_loop.run_until_complete(main(event_loop))
    29. finally:
    30. event_loop.close()

    捕捉异常会提供一个机会,如果必要,可以利用这个机会清理已经完成的工作。

     

    1.5.3 从协程创建任务

    ensure_future()函数返回一个与协程执行绑定的Task。这个Task实例再传递到其他代码,这个代码可以等待这个实例,而无须知道原来的协程是如何构造或调用的。

    
    
    1. import asyncio
    2.  
    3. async def wrapped():
    4. print('wrapped')
    5. return 'result'
    6.  
    7. async def inner(task):
    8. print('inner: starting')
    9. print('inner: waiting for {!r}'.format(task))
    10. result = await task
    11. print('inner: task returned {!r}'.format(result))
    12.  
    13. async def starter():
    14. print('starter: creating task')
    15. task = asyncio.ensure_future(wrapped())
    16. print('starter: waiting for inner')
    17. await inner(task)
    18. print('starter: inner returned')
    19.  
    20. event_loop = asyncio.get_event_loop()
    21. try:
    22. print('entering event loop')
    23. result = event_loop.run_until_complete(starter())
    24. finally:
    25. event_loop.close()

    需要说明,对于提供给ensure_future()的协程,在使用await之前这个协程不会启动,只有await才会让它执行。

    1.6 组合协程和控制结构

    一系列协程之间的线性控制流用内置关键字await可以很容易地管理。更复杂的结构可能允许一个协程等待多个其他协程并行完成,可以使用asyncio中的工具创建这些更复杂的结构。

    1.6.1 等待多个协程

    通常可以把一个操作划分为多个部分,然后分别执行,这会很有用。例如,采用这种方法,可以高效地下载多个远程资源或者查询远程API。有些情况下,执行顺序并不重要,而且可能有任意多个操作,可以使用wait()暂停一个协程,直到其他后台操作完成。

    
    
    1. import asyncio
    2.  
    3. async def phase(i):
    4. print('in phase {}'.format(i))
    5. await asyncio.sleep(0.1 * i)
    6. print('done with phase {}'.format(i))
    7. return 'phase {} result'.format(i)
    8.  
    相关教程