在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 相关文章推荐
python3.0 字典key排序
Dec 24 Python
Python中用Decorator来简化元编程的教程
Apr 13 Python
python获取list下标及其值的简单方法
Sep 12 Python
Python json 错误xx is not JSON serializable解决办法
Mar 15 Python
Python基于matplotlib实现绘制三维图形功能示例
Jan 18 Python
django中的HTML控件及参数传递方法
Mar 20 Python
numpy的文件存储.npy .npz 文件详解
Jul 09 Python
python redis 删除key脚本的实例
Feb 19 Python
pyinstaller打包单个exe后无法执行错误的解决方法
Jun 21 Python
用django设置session过期时间的方法解析
Aug 05 Python
python聚类算法解决方案(rest接口/mpp数据库/json数据/下载图片及数据)
Aug 28 Python
python实现秒杀商品的微信自动提醒功能(代码详解)
Apr 27 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
使用TinyButStrong模板引擎来做WEB开发
2007/03/16 PHP
什么是MVC,好东西啊
2007/05/03 PHP
解析php中var_dump,var_export,print_r三个函数的区别
2013/06/21 PHP
php制作中间带自己定义图片二维码的方法
2014/01/27 PHP
php导出中文内容excel文件类实例
2015/07/06 PHP
PHP基于rabbitmq操作类的生产者和消费者功能示例
2018/06/16 PHP
Jquery知识点二 jquery下对数组的操作
2011/01/15 Javascript
js中window.open()的所有参数详细解析
2014/01/09 Javascript
JavaScript监听和禁用浏览器回车事件实例
2015/01/31 Javascript
js简单实现标签云效果实例
2015/08/06 Javascript
javascript实现瀑布流加载图片原理
2016/02/02 Javascript
Vue.js实现输入框绑定的实例代码
2017/08/24 Javascript
angular4 共享服务在多个组件中数据通信的示例
2018/03/30 Javascript
javascript使用正则实现去掉字符串前面的所有0
2018/07/23 Javascript
vue操作下拉选择器获取选择的数据的id方法
2018/08/24 Javascript
微信小程序云开发如何使用npm安装依赖
2019/05/18 Javascript
使用vue自定义指令开发表单验证插件validate.js
2019/05/23 Javascript
在vue-cli3.0 中使用预处理器 (Sass/Less/Stylus) 配置全局变量操作
2020/08/10 Javascript
[01:31]完美与DOTA2历程
2014/07/31 DOTA
[02:29]完美世界高校联赛上海赛区回顾
2015/12/15 DOTA
Python性能优化的20条建议
2014/10/25 Python
Python 递归函数详解及实例
2016/12/27 Python
Python中常见的异常总结
2018/02/20 Python
Python简单实现两个任意字符串乘积的方法示例
2018/04/12 Python
Python Numpy 控制台完全输出ndarray的实现
2020/02/19 Python
python中前缀运算符 *和 **的用法示例详解
2020/05/28 Python
python subprocess pipe 实时输出日志的操作
2020/12/05 Python
Expedia爱尔兰:酒店、机票、租车及廉价假期
2017/01/02 全球购物
Marlies Dekkers内衣美国官方网上商店:高端内衣品牌
2018/11/12 全球购物
英国领先的互联网葡萄酒礼品商:Vintage Wine & Port
2019/05/24 全球购物
校园自助餐厅的创业计划书
2013/12/26 职场文书
经典演讲稿汇总
2014/05/19 职场文书
优秀应届生求职信
2014/06/16 职场文书
甲乙双方合作协议书
2014/10/13 职场文书
2015年英语教学工作总结
2015/05/25 职场文书
Python中可变和不可变对象的深入讲解
2021/08/02 Python