python3 asyncio-协程模块测试代码

import time

import asyncio

#统计运行时间的装饰器
def run_time(func):
    def wrapperfunc(*argv, **kwargv):
        now = lambda : time.time()
        start = now()
        func(*argv, **kwargv)
        end = now()
        runTime = end - start
        print("")
        print("run_time:{}s".format(runTime))
    return wrapperfunc

#程序运行区域划分
def printf(func):
    def wrapperfunc(*argv, **kwargv):
        print("start:***********")
        func(*argv, **kwargv)
        print("end:*************")
    return wrapperfunc


async def do_some_work(x):
    time.sleep(0.5)
    print("waiting: ", x)
    await asyncio.sleep(x)
    print("complete: ", x)
    return 'Done after {}s'.format(x)

async def hong():
    print("waiting: ", 5)
    await asyncio.sleep(5)
    return "ok"

#获得协程处理完毕后的结果
def test(io):
    print("")
    print("协程回调功能测试")
    print(type(io), "-----"+str(io))
    print("get:", io.result())
    print("")
    
def test1(t, future, *argv):
    print("callback", t, future.result())

async def east():
    #协程重新命名方便进行列表构建
    north1 = do_some_work(1)
    north2 = do_some_work(2)
    north3 = do_some_work(4)
    north4 = hong()
    #创建task对象,可以获得协程运行后的结果
    task4 = asyncio.ensure_future(north1)
    task5 = asyncio.ensure_future(north2)
    task6 = asyncio.ensure_future(north3)
    task7 = asyncio.ensure_future(north4)
    #协程task4处理完成后,调用test函数
    task4.add_done_callback(test)

    tasks = [task4, task5, task6,task7]
    return await asyncio.wait(tasks)

@printf
@run_time
def main(a):
    loop = asyncio.get_event_loop()
    tasks, _ = loop.run_until_complete(east())
    print("")
    print("查看协程处理完毕后,保存的结果")
    for task in tasks:
        print(task.result())

main("lk")
原文地址:https://www.cnblogs.com/by2016/p/6433961.html