在python里使用await关键字来等另外一个协程的实例


Posted in Python onMay 04, 2020

一个协程里可以启动另外一个协程,并等待它完成返回结果,采用await关键字,

例子如下:

import asyncio
 
async def outer():
  print('in outer')
  print('waiting for result1')
  result1 = await phase1()
  print('waiting for result2')
  result2 = await phase2(result1)
  return (result1, result2)
 
async def phase1():
  print('in phase1')
  return 'result1'
 
async def phase2(arg):
  print('in phase2')
  return 'result2 derived from {}'.format(arg)
 
event_loop = asyncio.get_event_loop()
try:
  return_value = event_loop.run_until_complete(outer())
  print('return value: {!r}'.format(return_value))
finally:
  event_loop.close()

输出结果如下:
in outer
waiting for result1
in phase1
waiting for result2
in phase2
return value: ('result1', 'result2 derived from result1')

await关键字添加了一个新的协程到循环里,而不需要明确地添加协程到这个事件循环里。

补充知识:python里使用Condition对象来唤醒指定数量的协程

在asyncio库里,定义Condition对象,它的行为与事件Event有点像,区别是事件是通知所有对象,Condition对象可以指定一定数量的协程被通知,它是通过函数notify()来实现的,如果参数里放2,就是通知两个协程,例子如下:

import asyncio
 
async def consumer(condition, n):
  with await condition:
    print('consumer {} is waiting'.format(n))
    await condition.wait()
    print('consumer {} triggered'.format(n))
  print('ending consumer {}'.format(n))
 
async def manipulate_condition(condition):
  print('starting manipulate_condition')
 
  # pause to let consumers start
  await asyncio.sleep(0.1)
 
  for i in range(1, 3):
    with await condition:
      print('notifying {} consumers'.format(i))
      condition.notify(n=i)
    await asyncio.sleep(0.1)
 
  with await condition:
    print('notifying remaining consumers')
    condition.notify_all()
 
  print('ending manipulate_condition')
 
async def main(loop):
  # Create a condition
  condition = asyncio.Condition()
 
  # Set up tasks watching the condition
  consumers = [
    consumer(condition, i)
    for i in range(5)
  ]
 
  # Schedule a task to manipulate the condition variable
  loop.create_task(manipulate_condition(condition))
 
  # Wait for the consumers to be done
  await asyncio.wait(consumers)
 
event_loop = asyncio.get_event_loop()
try:
  result = event_loop.run_until_complete(main(event_loop))
finally:
  event_loop.close()

结果输出如下:

starting manipulate_condition
consumer 2 is waiting
consumer 3 is waiting
consumer 4 is waiting
consumer 1 is waiting
consumer 0 is waiting
notifying 1 consumers
consumer 2 triggered
ending consumer 2
notifying 2 consumers
consumer 3 triggered
ending consumer 3
consumer 4 triggered
ending consumer 4
notifying remaining consumers
ending manipulate_condition
consumer 1 triggered
ending consumer 1
consumer 0 triggered
ending consumer 0

以上这篇在python里使用await关键字来等另外一个协程的实例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持三水点靠木。

Python 相关文章推荐
Python文件操作之合并文本文件内容示例代码
Sep 19 Python
Python实现获取前100组勾股数的方法示例
May 04 Python
Opencv+Python实现图像运动模糊和高斯模糊的示例
Apr 11 Python
局域网内python socket实现windows与linux间的消息传送
Apr 19 Python
Python列表与元组的异同详解
Jul 02 Python
pip 安装库比较慢的解决方法(国内镜像)
Oct 06 Python
Django实现网页分页功能
Oct 31 Python
Django 自动生成api接口文档教程
Nov 19 Python
Python 日期时间datetime 加一天,减一天,加减一小时一分钟,加减一年
Apr 16 Python
TensorFlow的环境配置与安装教程详解(win10+GeForce GTX1060+CUDA 9.0+cuDNN7.3+tensorflow-gpu 1.12.0+python3.5.5)
Jun 22 Python
matplotlib基础绘图命令之bar的使用方法
Aug 13 Python
Python猫眼电影最近上映的电影票房信息
Sep 18 Python
python 异步async库的使用说明
May 04 #Python
Python插件机制实现详解
May 04 #Python
python3+selenium获取页面加载的所有静态资源文件链接操作
May 04 #Python
解决IDEA 的 plugins 搜不到任何的插件问题
May 04 #Python
python3 sleep 延时秒 毫秒实例
May 04 #Python
Python并发concurrent.futures和asyncio实例
May 04 #Python
Python 中由 yield 实现异步操作
May 04 #Python
You might like
实用函数9
2007/11/08 PHP
PHP中设置时区方法小结
2012/06/03 PHP
php 无限级分类 获取顶级分类ID
2016/03/13 PHP
php将一维数组转换为每3个连续值组成的二维数组
2016/05/06 PHP
PHPstorm快捷键(分享)
2017/07/17 PHP
使用javascript:将其它类型值转换成布尔类型值的解决方法详解
2013/05/07 Javascript
快速解决jQuery与其他库冲突的方法介绍
2014/01/02 Javascript
node.js中的require使用详解
2014/12/15 Javascript
JS获取及验证开始结束日期的方法
2016/08/20 Javascript
jQuery如何防止Ajax重复提交
2016/10/14 Javascript
概述BootStrap中role="form"及role作用角色
2016/12/08 Javascript
微信小程序 引入es6 promise
2017/04/12 Javascript
JavaScript实现网页头部进度条刷新
2017/04/16 Javascript
详解Vue 全局引入bass.scss 处理方案
2018/03/26 Javascript
Vue.js获取被选择的option的value和text值方法
2018/08/24 Javascript
Angular动态绑定样式及改变UI框架样式的方法小结
2018/09/03 Javascript
webpack打包nodejs项目的方法
2018/09/26 NodeJs
vue实现扫码功能
2020/01/17 Javascript
八种Vue组件间通讯方式合集(推荐)
2020/08/18 Javascript
uniapp电商小程序实现订单30分钟倒计时
2020/11/01 Javascript
[01:31](回顾)杀出重围,决战TI之巅
2014/07/01 DOTA
用PyQt进行Python图形界面的程序的开发的入门指引
2015/04/14 Python
分析Python中设计模式之Decorator装饰器模式的要点
2016/03/02 Python
Linux下python3.7.0安装教程
2018/07/30 Python
python绘制漏斗图步骤详解
2019/03/04 Python
Python中的十大图像处理工具(小结)
2019/06/10 Python
Python datetime包函数简单介绍
2019/08/28 Python
python3中使用__slots__限定实例属性操作分析
2020/02/14 Python
Python unittest单元测试框架及断言方法
2020/04/15 Python
某公司C#程序员面试题笔试题
2014/05/26 面试题
人力资源管理专业应届生求职信
2013/09/28 职场文书
个人自我鉴定写法
2013/11/30 职场文书
创业计划书的主要内容有哪些
2014/01/29 职场文书
机关驾驶员违规检讨书
2014/09/13 职场文书
解决Pytorch半精度浮点型网络训练的问题
2021/05/24 Python
nginx从安装到配置详细说明(安装,安全配置,防盗链,动静分离,配置 HTTPS,性能优化)
2022/02/12 Servers