Python异步编程Async/Awai

2020-01-09 10:11:17 浏览数 (2)

python 从3.5开始从语言层面提供了新的异步编程语法。

代码语言:javascript复制
import asyncio


async def hello():
    print("hello the world")
    r = await asyncio.sleep(1)
    print("hello again")

def main():
    loop = asyncio.get_event_loop()
    """
    tasks = [
        asyncio.ensure_future(hello()),
    ]
    loop.run_until_complete(asyncio.wait(tasks))
    """
    print("begin")
    loop.run_until_complete(hello())
    print("end")
    loop.close()

    print("program is finished.")


if __name__ == "__main__":
    main()

0 人点赞