Python协程

先理解协程(协程有多种写法,效果都是一样得),来自廖雪峰和评论
在这里插入图片描述
输出为:
在这里插入图片描述

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
对于开头得理解解释:
在这里插入图片描述
在这里插入图片描述
下面一些截图来自B站得协程教学视频
Python3.7+协程一般的写法
Python3.7官方文档

async定义,await + 可等待对象用(协程对象,Future,Task对象),asyncio.run()运行协程

单个任务

import asyncio

async def a():
    print('aaaa')
    await asyncio.sleep(1)
    print('end')
    return 'return'

print(asyncio.run(a()))

在这里插入图片描述
多个任务(使用task)
在这里插入图片描述
等价成下面这个
在这里插入图片描述
Python3.7之前协程的写法

import asyncio

async def hello_world():
    print("Hello World!")

loop = asyncio.get_event_loop()
# Blocking call which returns when the hello_world() coroutine is done
loop.run_until_complete(hello_world())
loop.close()

官方例子:

python3.6文档
在这里插入图片描述
过程图解
在这里插入图片描述

Task对象文档解释

在这里插入图片描述

Future对象

async def set_after(fut, delay, value):
    # Sleep for *delay* seconds.
    await asyncio.sleep(delay)

    # Set *value* as a result of *fut* Future.
    fut.set_result(value)

async def main():
    # Get the current event loop.
    loop = asyncio.get_running_loop()

    # Create a new Future object.
    fut = loop.create_future()

    # Run "set_after()" coroutine in a parallel Task.
    # We are using the low-level "loop.create_task()" API here because
    # we already have a reference to the event loop at hand.
    # Otherwise we could have just used "asyncio.create_task()".
    loop.create_task(
        set_after(fut, 1, '... world'))

    print('hello ...')

    # Wait until *fut* has a result (1 second) and print it.
    print(await fut)

asyncio.run(main())

concurrent.futures.Future对象

在这里插入图片描述

在这里插入图片描述

异步io+不支持异步的 使用上述方法实行

ex1: asyncio+requests进行爬虫

在这里插入图片描述

asyncio异步迭代器

在这里插入图片描述

asyncio异步上下文管理

在这里插入图片描述
进度

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值