在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中__call__内置函数用法实例
Jun 04 Python
python实现windows下文件备份脚本
May 27 Python
详解python中的hashlib模块的使用
Apr 22 Python
简单了解python的内存管理机制
Jul 08 Python
python之生产者消费者模型实现详解
Jul 27 Python
python-web根据元素属性进行定位的方法
Dec 13 Python
如何使用python3获取当前路径及os.path.dirname的使用
Dec 13 Python
python Manager 之dict KeyError问题的解决
Dec 21 Python
python使用for...else跳出双层嵌套循环的方法实例
May 17 Python
Python文件操作模拟用户登陆代码实例
Jun 09 Python
如何编写python的daemon程序
Jan 07 Python
python中编写函数并调用的知识点总结
Jan 13 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 修改、增加xml结点属性的实现代码
2013/10/22 PHP
PHP自带ZIP压缩、解压缩类ZipArchiv使用指南
2015/03/03 PHP
php类中的$this,static,final,const,self这几个关键字使用方法
2015/12/14 PHP
JavaScript Event学习第三章 早期的事件处理程序
2010/02/07 Javascript
基于JQuery实现CheckBox全选全不选
2011/06/27 Javascript
纯js实现仿QQ邮箱弹出确认框
2015/04/29 Javascript
JavaScript直播评论发弹幕切图功能点集合效果代码
2016/06/26 Javascript
js中window.open的参数及注意注意事项
2016/07/06 Javascript
浅谈js内置对象Math的属性和方法(推荐)
2016/09/19 Javascript
基于NodeJS+MongoDB+AngularJS+Bootstrap开发书店案例分析
2017/01/12 NodeJs
JavaScript正则表达式替换字符串中图片地址(img src)的方法
2017/01/13 Javascript
Vue项目组件化工程开发实践方案
2018/01/09 Javascript
JavaScript获取用户所在城市及地理位置
2018/04/21 Javascript
JS call()及apply()方法使用实例汇总
2020/07/11 Javascript
Python获取电脑硬件信息及状态的实现方法
2014/08/29 Python
python安装oracle扩展及数据库连接方法
2017/02/21 Python
解决Linux系统中python matplotlib画图的中文显示问题
2017/06/15 Python
Django中的CBV和FBV示例介绍
2018/02/25 Python
python实现图片彩色转化为素描
2019/01/15 Python
keras 特征图可视化实例(中间层)
2020/01/24 Python
python3读取autocad图形文件.py实例
2020/06/05 Python
python怎么删除缓存文件
2020/07/19 Python
深入了解Python 变量作用域
2020/07/24 Python
2020年10款优秀的Python第三方库,看看有你中意的吗?
2021/01/12 Python
CSS3 中的@keyframes介绍
2014/09/02 HTML / CSS
详解移动端h5页面根据屏幕适配的四种方案
2020/04/15 HTML / CSS
介绍一下SQL中union,intersect和minus
2012/04/05 面试题
幼儿园教育教学反思
2014/01/31 职场文书
学生手册家长评语
2014/02/10 职场文书
建筑工地门卫岗位职责
2014/04/30 职场文书
2014基层党员批评与自我批评范文
2014/09/24 职场文书
2014年小学教研工作总结
2014/12/06 职场文书
全陪导游词开场白
2015/05/29 职场文书
初三英语教学反思
2016/02/15 职场文书
【DOTA2】半决赛强强对话~ PSG LGD vs EHOME - DPC 2022 CN REGIONAL FINALS WINTER
2022/04/02 DOTA
python实现双链表
2022/05/25 Python