• 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")
  • 相关阅读:
    Codeforces Round #437 (Div. 2, based on MemSQL Start[c]UP 3.0
    Codeforces 294C 组合数学
    Educational Codeforces Round 40 (Rated for Div. 2)
    第13届景驰-埃森哲杯广东工业大学ACM程序设计大赛
    天梯赛和蓝桥杯省赛训练
    莫队算法
    牛客练习赛13
    51NOD-1391 预处理dp
    AtCoder Regular Contest 092
    大二下学期赛季
  • 原文地址:https://www.cnblogs.com/by2016/p/6433961.html
Copyright © 2020-2023  润新知