Python 异步库asyncio 的简单使用说明

import asyncio # python3.4之后自带的标准库

async def f1 (url, delay):
    await asyncio.sleep(delay)
    print ("Fetch %s " % url)
    return f"<html>{url}"

def main():
    '''
    输出: begin
    输出: Fetch sogou.com
    输出: Fetch baidu.com
    返回: ['<html>baidu.com', '<html>sogou.com']

    执行步骤:
        输出begin
        第3秒输出Fetch sogou.com
        第10秒输出Fetch baidu.com
        第10秒返回['<html>baidu.com', '<html>sogou.com']

    调试:
        输出begin
        第0秒,执行f1('baidu.com', 10)
            遇到sleep, 记住10秒后再往下执行,切换到其他协程
        第0秒,执行f1('sogou.com', 3)
            遇到sleep, 记住3秒后再往下执行,切换到其他协程
        第3秒后
            继续f1('sogou.com', 3) sleep下面的代码 (输出: Fetch sogou.com)
        第10秒后
            继续f1('baidu.com', 10) sleep下面的代码 (输出: Fetch baidu.com)
        一起返回返回值

    '''
    print ('begin')
    loop = asyncio.get_event_loop()
    results = loop.run_until_complete(asyncio.gather(
        f1('baidu.com', 10),
        f1('sogou.com', 3)))
    print (results)


if __name__ == "__main__":
    main()

asyncio 异步, 调用异步函数要使用await ,使用了await 的函数外面要用async,这要成对出现的。

上面的代码,遇到await sleep时,cpu会切换执行其他的协程,等sleep完成后,再执行当前协程后面的代码。

猜你喜欢

转载自blog.csdn.net/makao007/article/details/127997893
今日推荐