在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中MySQLdb模块用法实例
Nov 10 Python
Python日志模块logging简介
Apr 13 Python
详解C++编程中一元运算符的重载
Jan 19 Python
用python写一个windows下的定时关机脚本(推荐)
Mar 21 Python
Python探索之Metaclass初步了解
Oct 28 Python
浅谈python迭代器
Nov 08 Python
python实现装饰器、描述符
Feb 28 Python
总结python中pass的作用
Feb 27 Python
python代码打印100-999之间的回文数示例
Nov 24 Python
PyTorch中topk函数的用法详解
Jan 02 Python
浅谈Python3多线程之间的执行顺序问题
May 02 Python
Python爬虫+tkinter界面实现历史天气查询的思路详解
Feb 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
自己做矿石收音机
2021/03/02 无线电
《PHP边学边教》(02.Apache+PHP环境配置――上篇)
2006/12/13 PHP
php实现按文件名搜索文件的远程文件查找器
2014/05/10 PHP
php+Mysqli利用事务处理转账问题实例
2015/02/11 PHP
php使用文本统计访问量的方法
2016/05/12 PHP
Jsonp 跨域的原理以及Jquery的解决方案
2010/05/18 Javascript
Jquery常用技巧收集整理篇
2010/11/14 Javascript
jQuery向webApi提交post json数据
2017/01/16 Javascript
javascript事件的绑定基础实例讲解(34)
2017/02/14 Javascript
创建简单的node服务器实例(分享)
2017/06/23 Javascript
浅析JS中常用类型转换及运算符表达式
2017/07/23 Javascript
element-ui表格数据转换的示例代码
2018/08/24 Javascript
Vue项目部署的实现(阿里云+Nginx代理+PM2)
2019/03/26 Javascript
Vue+Element UI+vue-quill-editor富文本编辑器及插入图片自定义
2019/08/20 Javascript
原生JS实现贪吃蛇小游戏
2020/03/09 Javascript
vue使用map代替Aarry数组循环遍历的方法
2020/04/30 Javascript
nodejs使用Sequelize框架操作数据库的实现
2020/10/21 NodeJs
详解Vue3 Teleport 的实践及原理
2020/12/02 Vue.js
[01:45]绝对公平!DOTA2队长征召模式详解
2014/04/25 DOTA
[07:55]2014DOTA2 TI正赛第三日 VG上演推进荣耀DKEG告别
2014/07/21 DOTA
python中精确输出JSON浮点数的方法
2014/04/18 Python
python 绘制拟合曲线并加指定点标识的实现
2019/07/10 Python
Python实现最常见加密方式详解
2019/07/13 Python
Python彻底删除文件夹及其子文件方式
2019/12/23 Python
Keras设置以及获取权重的实现
2020/06/19 Python
python可视化分析的实现(matplotlib、seaborn、ggplot2)
2021/02/03 Python
探究 canvas 绘图中撤销(undo)功能的实现方式详解
2018/05/17 HTML / CSS
超级英雄、电影和电视、乐队和音乐T恤:Loud Clothing
2019/09/01 全球购物
一些Solaris面试题
2013/03/22 面试题
研究生求职推荐信范文
2013/11/30 职场文书
旺仔牛奶广告词
2014/03/20 职场文书
项目经理任命书范本
2014/06/05 职场文书
工作失误检讨书
2015/01/26 职场文书
2015年教育实习工作总结
2015/04/24 职场文书
Nginx已编译的nginx-添加新模块
2021/04/01 Servers
MySQL Router实现MySQL的读写分离的方法
2021/05/27 MySQL