Python 高级编程和异步IO并发编程 --13_3 task取消与子协程调用

#1. run_until_complete
import asyncio
loop = asyncio.get_event_loop()
loop.run_forever()
loop.run_until_complete()

# loop会被放到future中。
#2 取消future(task)
import asyncio
import time

async def get_html(sleep_times):
    print("waitting")
    await asyncio.sleep(sleep_times)
    print("done after {}s".format(sleep_times))

if __name__=="__main__":
    task1 = get_html(2)
    task2 = get_html(3)
    task3 = get_html(3)

    tasks = [task1,task2,task3]
    
    loop = asyncio.get_event_loop()
    
    loop.run_until_complete(asyncio.wait(tasks))
waitting
waitting
waitting
done after 2s
done after 3s
done after 3s
#2 取消future(task)
import asyncio
import time

async def get_html(sleep_times):
    print("waitting")
    await asyncio.sleep(sleep_times)
    print("done after {}s".format(sleep_times))

if __name__=="__main__":
    task1 = get_html(2)
    task2 = get_html(3)
    task3 = get_html(3)

    tasks = [task1,task2,task3]

    loop = asyncio.get_event_loop()

    try:
        loop.run_until_complete(asyncio.wait(tasks))
    except KeyboardInterrupt as e:  # 外部按下ctrl+c中止执行
        all_tasks = asyncio.Task.all_tasks()
        for task in all_tasks:
            print("cancel task")
            print(task.cancel())
        loop.stop()
        loop.run_forever()
    finally:
        loop.close()
# 协程嵌套
import asyncio

async def compute(x,y):
    print("Compute %s + %s..."%(x,y))
    await asyncio.sleep(1.0)
    return x+y

async def print_sum(x,y):
    result = await compute(x,y)
    print("%s + %s = %s"%(x,y,result))

loop = asyncio.get_event_loop()
loop.run_until_complete(print_sum(1,2))
loop.close()
Compute 1 + 2...
1 + 2 = 3

发布了380 篇原创文章 · 获赞 129 · 访问量 11万+

猜你喜欢

转载自blog.csdn.net/f2157120/article/details/105356273