在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中使用dom模块生成XML文件示例
Apr 05 Python
Python 打印中文字符的三种方法
Aug 14 Python
关于Pycharm无法debug问题的总结
Jan 19 Python
Python直接赋值、浅拷贝与深度拷贝实例分析
Jun 18 Python
如何使用python把ppt转换成pdf
Jun 29 Python
python解析yaml文件过程详解
Aug 30 Python
python elasticsearch环境搭建详解
Sep 02 Python
Python3 字典dictionary入门基础附实例
Feb 10 Python
logging level级别介绍
Feb 21 Python
详解PyQt5中textBrowser显示print语句输出的简单方法
Aug 07 Python
python实现人工蜂群算法
Sep 18 Python
python动态规划算法实例详解
Nov 22 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
php验证手机号码
2015/11/11 PHP
详解在PHP的Yii框架中使用行为Behaviors的方法
2016/03/18 PHP
php及codeigniter使用session-cookie的方法(详解)
2017/04/06 PHP
yii gridview实现时间段筛选功能
2017/08/15 PHP
laravel框架使用FormRequest进行表单验证,验证异常返回JSON操作示例
2020/02/18 PHP
php实现的证件照换底色功能示例【人像抠图/换背景图】
2020/05/29 PHP
jQuery 页面 Mask实现代码
2010/01/09 Javascript
node.js中的fs.readlink方法使用说明
2014/12/17 Javascript
不同js异步函数同步的实现方法
2016/05/28 Javascript
jQuery在header中设置请求信息的方法
2017/03/06 Javascript
canvas绘制一个常用的emoji表情
2017/03/30 Javascript
javascript回调函数的概念理解与用法分析
2017/05/27 Javascript
Express框架之connect-flash详解
2017/05/31 Javascript
React组件之间的通信的实例代码
2017/06/27 Javascript
node+multer实现图片上传的示例代码
2020/02/18 Javascript
JQuery省市联动效果实现过程详解
2020/05/08 jQuery
使用Python & Flask 实现RESTful Web API的实例
2017/09/19 Python
Tensorflow模型实现预测或识别单张图片
2019/07/19 Python
打包PyQt5应用时的注意事项
2020/02/14 Python
Python常用编译器原理及特点解析
2020/03/23 Python
css3.0 图形构成实例练习一
2013/03/19 HTML / CSS
css3 伪元素和伪类选择器详解
2014/09/04 HTML / CSS
html5 canvas-2.用canvas制作一个猜字母的小游戏
2013/01/07 HTML / CSS
瑞典时尚耳机品牌:Urbanears
2017/07/26 全球购物
卡拉威高尔夫官方网站:Callaway Golf
2020/09/16 全球购物
Genny意大利官网:意大利高级时装品牌
2020/04/15 全球购物
联想智利官方网站:Lenovo Chile
2020/06/03 全球购物
中文系学生自荐信范文
2013/11/13 职场文书
甲方资料员岗位职责
2013/12/13 职场文书
大学辅导员事迹材料
2014/02/05 职场文书
英语专业自荐书
2014/06/13 职场文书
教师三严三实心得体会
2014/10/11 职场文书
向雷锋同志学习倡议书
2015/04/27 职场文书
政协常委会议主持词
2015/07/03 职场文书
如何书写邀请函?
2019/06/24 职场文书
Python Matplotlib绘制两个Y轴图像
2022/04/13 Python