在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中pygame模块的Linux下安装过程(详解)
Nov 09 Python
python实现字符串加密 生成唯一固定长度字符串
Mar 22 Python
Python3+OpenCV2实现图像的几何变换(平移、镜像、缩放、旋转、仿射)
May 13 Python
python批量爬取下载抖音视频
Jun 17 Python
django框架使用views.py的函数对表进行增删改查内容操作详解【models.py中表的创建、views.py中函数的使用,基于对象的跨表查询】
Dec 12 Python
Python迷宫生成和迷宫破解算法实例
Dec 24 Python
Pycharm+Python工程,引用子模块的实现
Mar 09 Python
python读取yaml文件后修改写入本地实例
Apr 27 Python
Python 程序报错崩溃后如何倒回到崩溃的位置(推荐)
Jun 23 Python
Python wordcloud库安装方法总结
Dec 31 Python
python中pyqtgraph知识点总结
Jan 26 Python
python 爬取吉首大学网站成绩单
Jun 02 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
自制汽车收音机天线:收听广播的技巧和方法
2021/03/02 无线电
discuz的php防止sql注入函数
2011/01/17 PHP
php中使用DOM类读取XML文件的实现代码
2011/12/14 PHP
PHP使用PHPexcel导入导出数据的方法
2015/11/14 PHP
JavaScript实现删除电脑的关机键
2016/07/26 PHP
php 根据URL下载远程图片、压缩包、pdf等文件到本地
2019/07/26 PHP
jQuery动态地获取系统时间实现代码
2013/05/24 Javascript
JS文本获得焦点清除文本文字的示例代码
2014/01/13 Javascript
JS中使用Array函数shift和pop创建可忽略参数的例子
2014/05/28 Javascript
用js传递value默认值的示例代码
2014/09/11 Javascript
JavaScript的RequireJS库入门指南
2015/07/01 Javascript
Bootstrap菜单按钮及导航实例解析
2016/09/09 Javascript
JavaScript简单下拉菜单特效
2016/09/13 Javascript
JavaScript 判断一个对象{}是否为空对象的简单方法
2016/10/09 Javascript
浅谈Vue.js
2017/03/02 Javascript
JS模拟实现ECMAScript5新增的数组方法
2017/03/20 Javascript
Vue2.0设置全局样式(less/sass和css)
2017/11/18 Javascript
深入浅析Node环境和浏览器的区别
2018/08/14 Javascript
关于JavaScript 数组你应该知道的事情(推荐)
2019/04/10 Javascript
js对象数组和对象的使用实例详解
2019/08/27 Javascript
Node.js实现简单管理系统
2019/09/23 Javascript
wxPython中listbox用法实例详解
2015/06/01 Python
Python爬取qq music中的音乐url及批量下载
2017/03/23 Python
Tensorflow之构建自己的图片数据集TFrecords的方法
2018/02/07 Python
python根据文章标题内容自动生成摘要的实例
2019/02/21 Python
Python创建或生成列表的操作方法
2019/06/19 Python
PyQt5根据控件Id获取控件对象的方法
2019/06/25 Python
使用python爬取微博数据打造一颗“心”
2019/06/28 Python
Python实现上下文管理器的方法
2020/08/07 Python
Django haystack实现全文搜索代码示例
2020/11/28 Python
CSS3模拟动画下拉菜单效果
2017/04/12 HTML / CSS
HTML5 播放 RTSP 视频的实例代码
2019/07/29 HTML / CSS
办理暂住证介绍信
2014/01/11 职场文书
毕业设计说明书
2014/05/07 职场文书
教师节主题班会方案
2015/08/17 职场文书
年终工作总结范文
2019/06/20 职场文书