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完成后,再执行当前协程后面的代码。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值