python async异步编程(二)

接着上一篇文章继续:https://www.cnblogs.com/liyuanhong/p/15600908.html

可参见官方文档:https://docs.python.org/zh-cn/3.7/library/asyncio-task.html

await关键字

 await后面可作用于以下内容:

  1. 携程对象
  2. feature
  3. Task队形
#coding: utf-8
import asyncio

async def func():
    print("aaaaaaaaaaaaa")
    response = await asyncio.sleep(2)
    print("over", response)

# 由于该函数加了async,所以是一个携程函数,执行他会返回一个携程对象
# 以下代码将该携程对象加入了事件循环中去执行
asyncio.run( func() )

 示例2:

# coding:utf-8

import asyncio

async def other():
    print("start")
    await  asyncio.sleep(2)
    print("end")
    return "response is 200"

async def func():
    print("执行携程函数内部代码")
    res1 = await other()      # 等待携程对象的值(及other返回值后),才执行后面的代码
    print("请求接结果res1:", res1)
    res2 = await other()
    print("请求接结果res2:", res2)

asyncio.run( func() )

执行结果如下:

执行携程函数内部代码
start
end
请求接结果res1: response is 200
start
end
请求接结果res2: response is 200

博客里大都是转载的内容,其目的主要用户知识的组织和管理。
原文地址:https://www.cnblogs.com/liyuanhong/p/15617141.html