在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实现树的先序、中序、后序排序算法示例
Jun 23 Python
Python类和对象的定义与实际应用案例分析
Dec 27 Python
Python面向对象程序设计类变量与成员变量、类方法与成员方法用法分析
Apr 12 Python
pyqt5 键盘监听按下enter 就登陆的实例
Jun 25 Python
ipython和python区别详解
Jun 26 Python
Python装饰器使用你可能不知道的几种姿势
Oct 25 Python
python GUI库图形界面开发之PyQt5 MDI(多文档窗口)QMidArea详细使用方法与实例
Mar 05 Python
详解PyQt5中textBrowser显示print语句输出的简单方法
Aug 07 Python
Python中常用的os操作汇总
Nov 05 Python
matplotlib制作雷达图报错ValueError的实现
Jan 05 Python
pycharm配置python 设置pip安装源为豆瓣源
Feb 05 Python
利用Python判断整数是否是回文数的3种方法总结
Jul 07 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.MVC的模板标签系统(二)
2006/09/05 PHP
PHP数据类型之布尔型的介绍
2013/04/28 PHP
php中strstr、strrchr、substr、stristr四个函数的区别总结
2014/09/22 PHP
20个2014年最优秀的PHP框架回顾
2014/10/22 PHP
PHP基于curl后台远程登录正方教务系统的方法
2016/10/14 PHP
php微信开发之关注事件
2018/06/14 PHP
laravel利用中间件做防非法登录和权限控制示例
2019/10/21 PHP
文本加密解密
2006/06/23 Javascript
尽可能写"友好"的"Javascript"代码
2007/01/09 Javascript
屏蔽F1~F12的快捷键的js函数
2010/05/06 Javascript
深入理解javascript学习笔记(一) 编写高质量代码
2012/08/09 Javascript
JavaScript网页定位详解
2014/01/13 Javascript
JavaScript截取字符串的2个函数介绍
2014/08/27 Javascript
JavaScript实现ASC转汉字及汉字转ASC的方法
2016/01/23 Javascript
详解EasyUi控件中的Datagrid
2017/08/23 Javascript
微信小程序顶部可滚动导航效果
2017/10/31 Javascript
JavaScript获取移动设备型号的实现代码(JS获取手机型号和系统)
2018/03/10 Javascript
对angularJs中$sce服务安全显示html文本的实例
2018/09/30 Javascript
vue路由--网站导航功能详解
2019/03/29 Javascript
在layui中对table中的数据进行判断(0、1)转换为提示信息的方法
2019/09/28 Javascript
JavaScript实现动态留言板
2020/03/16 Javascript
[05:00]第二届DOTA2亚洲邀请赛主赛事第三天比赛集锦.mp4
2017/04/04 DOTA
[37:02]OG vs INfamous 2019国际邀请赛小组赛 BO2 第二场 8.15
2019/08/17 DOTA
Python使用smtp和pop简单收发邮件完整实例
2018/01/09 Python
Django框架会话技术实例分析【Cookie与Session】
2019/05/24 Python
Python使用Matlab命令过程解析
2020/06/04 Python
Python 分布式缓存之Reids数据类型操作详解
2020/06/24 Python
欧洲著名的二手奢侈品网站:Vestiaire Collective
2020/03/07 全球购物
C&A巴西网上商店:时尚、衣服、手机和鞋子
2020/06/07 全球购物
abstract class和interface有什么区别?
2012/01/03 面试题
女方婚礼新郎答谢词
2014/01/11 职场文书
初中语文教学反思
2014/02/02 职场文书
村级个人对照检查材料
2014/08/22 职场文书
小学生大队委竞选稿
2015/11/20 职场文书
小学音乐课教学反思
2016/02/18 职场文书
分析Python感知线程状态的解决方案之Event与信号量
2021/06/16 Python