【12.2】task取消和子协程调用原理

task取消

 1 import asyncio
 2 import time
 3 
 4 
 5 async def get_html(sleep_time):
 6     print('waiting')
 7     await asyncio.sleep(sleep_time)
 8     print('done after {}s'.format(sleep_time))
 9 
10 
11 if __name__ == '__main__':
12     task1 = get_html(2)
13     task2 = get_html(3)
14     task3 = get_html(3)
15 
16     tasks = [task1, task2, task3]
17 
18     loop = asyncio.get_event_loop()
19 
20     try:
21         loop.run_until_complete(asyncio.gather(*tasks))
22     except KeyboardInterrupt as e:
23         # KeyboardInterrupt 是按Ctrl+C终止程序时抛出的异常
24         # 获取所有的task
25         all_tasks = asyncio.Task.all_tasks()
26         for task in all_tasks:
27             print('cancel task')
28             print(task.cancel())
29         loop.stop()
30         loop.run_forever()
31     finally:
32         loop.close()
waiting
waiting
waiting
cancel task
True
cancel task
True
cancel task
True

原文地址:https://www.cnblogs.com/zydeboke/p/11369709.html