Asyncio Python 编程代码实例, 同步函数的线程池实现异步, 迭代器异步, for 遍历异步 , 装饰器异步, 上下文管理器异步

import asyncio
import time
from contextlib import contextmanager, asynccontextmanager


async def fun(n):
    print(f"{fun.__name__}{n}")
    await asyncio.sleep(2)
    print(f"{fun.__name__}{n} end")
    return f"{fun.__name__}{n}"

async def foo(n):
    print(f"{foo.__name__}{n}")
    await asyncio.sleep(2)
    print(f"{foo.__name__}{n} end")
    return f"{foo.__name__}{n}"

# 记录运行时间装饰器
def record_time(func):
    async def wrapper(*args, **kwargs):
        t1 = time.time()
        await func(*args, **kwargs)
        print(f"decorator run time {time.time() - t1}")
    return wrapper

def print_number(n,cnt):
    start = n
    end = start + cnt
    for i in range(start, end):
        print(f"{print_number.__name__}:{i}")
        time.sleep(1)

async def set_future(fu):
    await asyncio.sleep(2)
    print("set future")
    fu.set_result("set future")


# 异步迭代器
class Incrementer:
    def __init__(self,start,cnt):
        self.i = start
        self.max = start + cnt

    def __aiter__(self):
        return self

    async def __anext__(self):
        if self.i < self.max:
            self.i += 1
            return f"{Incrementer.__name__}:{self.i}"
        else:
            raise StopAsyncIteration

async def async_for():
    async for i in Incrementer(1,5):
        print(i)
        await asyncio.sleep(1)

# 异步上下文管理器
class AsyncContextManagerClass:

    def __init__(self,wait_time):
        self.conn = "conn"
        self.wait_time_sec = wait_time

    async def wait_time(self):
        print(f"{AsyncContextManagerClass.__name__}: {self.wait_time_sec} sec")
        await asyncio.sleep(self.wait_time_sec)

    async def __aenter__(self):
        print(f"{AsyncContextManagerClass.__name__}:enter")
        return self

    async def __aexit__(self, exc_type, exc_val, exc_tb):
        print(f"{AsyncContextManagerClass.__name__}:exit")
        self.conn = None

# 异步上下文管理器函数半


class AsyncContextManagerFunction:
    def __init__(self,wait_time):
        self.wait_time = wait_time
        pass
    @asynccontextmanager
    async def async_context_manager(self):
        wait_time = self.wait_time
        print(f"{AsyncContextManagerFunction.__name__}:enter")
        time1 = asyncio.get_running_loop().time()
        await asyncio.sleep(wait_time)
        yield "conn"
        print(f"{AsyncContextManagerFunction.__name__}: {asyncio.get_running_loop().time() - time1}")
        print(f"{AsyncContextManagerFunction.__name__}:exit")

@record_time
async def main():
    print("main")
    # record run time
    loop = asyncio.get_running_loop()
    t1 = loop.time()

    task_list = [asyncio.create_task(fun(i)) for i in range(3)]
    task_list2 = [asyncio.create_task(foo(i)) for i in range(3)]

    fu = loop.create_future()


    # 创建一个异步函数后,可以立刻提交task执行,或者积攒到最后统一提交
    # 一个协程future对象只有在被设置值的时候才会返回/
    # loop.create_task(set_future(fu)) #
    # 如果一个异步函数不提交task,那么它就不会执行
    # set_future(fu)


    # print(z)
    # print_number(1,5)
    thread_future = loop.run_in_executor(None, print_number, 1, 5)
    # await thread_future
    # await fu




    # for task in task_list:
    #     await task
    # for task in task_list2:
    #     await task
    # time = 2.016
    wtt = AsyncContextManagerFunction(1)

    async with AsyncContextManagerClass(wait_time=2) as wt:
        async with wtt.async_context_manager() as wt2:
            print(wt2)
            total_task_list = task_list + task_list2 + \
                              [thread_future,
                               async_for(),
                               wt.wait_time()
                               # fu
                               ] + [
                                  set_future(fu),

                              ]

            done, pending = await asyncio.wait(total_task_list, timeout=1000, return_when=asyncio.ALL_COMPLETED)
    print("done", done)
    print("pending", pending)
    # time 2.015


    print("main end")
    print(f"run time {(loop.time() - t1)}")

asyncio.run(main())

你可能感兴趣的:(python,开发语言)