在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的Tornado框架对子域名和泛域名的支持
May 02 Python
关于Django显示时间你应该知道的一些问题
Dec 25 Python
Python多进程写入同一文件的方法
Jan 14 Python
Python实现钉钉发送报警消息的方法
Feb 20 Python
详解Python下载图片并保存本地的两种方式
May 15 Python
利用Python实现手机短信监控通知的方法
Jul 22 Python
python每天定时运行某程序代码
Aug 16 Python
Python 实现Serial 与STM32J进行串口通讯
Dec 18 Python
python识别验证码图片实例详解
Feb 17 Python
django-利用session机制实现唯一登录的例子
Mar 16 Python
Python爬虫:Request Payload和Form Data的简单区别说明
Apr 30 Python
Python四款GUI图形界面库介绍
Jun 05 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版(4)
2006/10/09 PHP
PHP读取MySQL数据代码
2008/06/05 PHP
thinkphp中session和cookie无效的解决方法
2014/12/19 PHP
在PHP程序中使用Rust扩展的方法
2015/07/03 PHP
thinkPHP框架中layer.js的封装与使用方法示例
2019/01/18 PHP
JavaScript 学习笔记 Black.Caffeine 09.11.28
2009/11/30 Javascript
javaScript call 函数的用法说明
2010/04/09 Javascript
Node.js抓取中文网页乱码问题和解决方法
2015/02/10 Javascript
javascript实现复选框选中属性
2015/03/25 Javascript
javascript实现简单的进度条
2015/07/02 Javascript
jQuery编写设置和获取颜色的插件
2017/01/09 Javascript
JavaScript解析JSON格式数据的方法示例
2017/01/24 Javascript
JS面试题大坑之隐式类型转换实例代码
2018/10/14 Javascript
JS浅拷贝和深拷贝原理与实现方法分析
2019/02/28 Javascript
Python实现抓取百度搜索结果页的网站标题信息
2015/01/22 Python
python处理html转义字符的方法详解
2016/07/01 Python
使用Python对MySQL数据操作
2017/04/06 Python
python中如何使用朴素贝叶斯算法
2017/04/06 Python
Python3生成手写体数字方法
2018/01/30 Python
python 3利用Dlib 19.7实现摄像头人脸检测特征点标定
2018/02/26 Python
python实现播放音频和录音功能示例代码
2018/12/30 Python
python 实现多维数组转向量
2019/11/30 Python
基于django2.2连oracle11g解决版本冲突的问题
2020/07/02 Python
澳大利亚在线消费电子产品商店:TobyDeals
2020/01/05 全球购物
Jar包的作用是什么
2014/03/30 面试题
介绍一下SQL Server里面的索引视图
2016/07/31 面试题
电气自动化自荐信
2013/10/10 职场文书
夜大毕业生自我鉴定
2013/10/31 职场文书
借款协议书范本
2014/04/22 职场文书
学校四风对照检查材料
2014/08/28 职场文书
2014年售票员工作总结
2014/11/19 职场文书
施工安全员岗位职责
2015/04/11 职场文书
仰望星空观后感
2015/06/10 职场文书
老干部局2015年度工作总结
2015/10/22 职场文书
JavaScript中时间格式化新思路toLocaleString()
2021/11/07 Javascript
Windows Server 2019 安装DHCP服务及相关配置
2022/04/28 Servers