在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使用smtplib模块通过gmail实现邮件发送的方法
May 08 Python
python解析基于xml格式的日志文件
Feb 25 Python
深入分析python中整型不会溢出问题
Jun 18 Python
使用python PIL库实现简单验证码的去噪方法步骤
May 10 Python
python 基于dlib库的人脸检测的实现
Nov 08 Python
python3中使用__slots__限定实例属性操作分析
Feb 14 Python
python异常处理、自定义异常、断言原理与用法分析
Mar 23 Python
Python装饰器实现方法及应用场景详解
Mar 26 Python
python 线程的五个状态
Sep 22 Python
Python控制台输出俄罗斯方块的方法实例
Apr 17 Python
python单元测试之pytest的使用
Jun 07 Python
基于Python实现一个春节倒计时脚本
Jan 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
玛琪朵 Macchiato
2021/03/03 咖啡文化
析构函数与php的垃圾回收机制详解
2013/10/28 PHP
WampServer下安装多个版本的PHP、mysql、apache图文教程
2015/01/07 PHP
PHP扩展开发入门教程
2015/02/26 PHP
Yii2下点击验证码的切换实例代码
2017/03/14 PHP
PHP环形链表实现方法示例
2017/09/15 PHP
PHP聚合式迭代器接口IteratorAggregate用法分析
2017/12/28 PHP
php unlink()函数使用教程
2018/07/12 PHP
理解Javascript_01_理解内存分配原理分析
2010/10/11 Javascript
JavaScript中去掉数组中的重复值的实现方法
2011/08/03 Javascript
jquery实现的带缩略图的焦点图片切换(自动播放/响应鼠标动作)
2013/01/23 Javascript
Extjs4 消息框去掉关闭按钮(类似Ext.Msg.alert)
2013/04/02 Javascript
浅谈jQuery构造函数分析
2015/05/11 Javascript
AngularJS教程之简单应用程序示例
2016/08/16 Javascript
jQuery Raty 一款不错的星级评分插件
2016/08/24 Javascript
Ionic + Angular.js实现图片轮播的方法示例
2017/05/21 Javascript
node.js中express中间件body-parser的介绍与用法详解
2017/05/23 Javascript
详解Angular中通过$location获取地址栏的参数
2018/08/02 Javascript
JavaScript查看代码运行效率console.time()与console.timeEnd()用法
2019/01/18 Javascript
vuejs实现下拉框菜单选择
2020/10/23 Javascript
微信小程序实现星星评分效果
2020/11/01 Javascript
python实现端口转发器的方法
2015/03/13 Python
Python使用面向对象方式创建线程实现12306售票系统
2015/12/24 Python
python实现搜索本地文件信息写入文件的方法
2016/02/22 Python
Python 类与元类的深度挖掘 II【经验】
2016/05/06 Python
Python3.X 线程中信号量的使用方法示例
2017/07/24 Python
python 读取txt中每行数据,并且保存到excel中的实例
2018/04/29 Python
python实现的按要求生成手机号功能示例
2019/10/08 Python
python中的Elasticsearch操作汇总
2019/10/30 Python
彻底解决pip下载pytorch慢的问题方法
2021/03/01 Python
css3实现书本翻页效果的示例代码
2021/03/08 HTML / CSS
咖啡店的创业计划书,让你hold不住
2014/01/03 职场文书
法律进企业活动方案
2014/03/04 职场文书
大学新闻系自荐书
2014/05/31 职场文书
抖音短视频(douyin)去水印工具的实现代码
2021/03/30 Javascript
go语言中切片与内存复制 memcpy 的实现操作
2021/04/27 Golang