在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程序语言快速上手教程
Jul 18 Python
利用Python脚本在Nginx和uwsgi上部署MoinMoin的教程
May 05 Python
将Python代码嵌入C++程序进行编写的实例
Jul 31 Python
Python编码类型转换方法详解
Jul 01 Python
Django使用HttpResponse返回图片并显示的方法
May 22 Python
基于python3 OpenCV3实现静态图片人脸识别
May 25 Python
在python中利用GDAL对tif文件进行读写的方法
Nov 29 Python
python 画3维轨迹图并进行比较的实例
Dec 06 Python
使用Python制作缩放自如的圣诞老人(圣诞树)
Dec 25 Python
tensorflow 实现从checkpoint中获取graph信息
Feb 10 Python
Python的in,is和id函数代码实例
Apr 18 Python
python实现将中文日期转换为数字日期
Jul 14 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 smarty模版引擎中变量操作符及使用方法
2009/12/11 PHP
php实现的pdo公共类定义与用法示例
2017/07/19 PHP
Yii框架中使用PHPExcel的方法分析
2019/07/25 PHP
yii2.0框架数据库操作简单示例【添加,修改,删除,查询,打印等】
2020/04/13 PHP
给jQuery方法添加回调函数一款插件的应用
2013/01/21 Javascript
基于jquery的9行js轻松实现tab控件示例
2013/10/12 Javascript
javascript阻止scroll事件多次执行的思路及实现
2013/11/08 Javascript
原生js实现模拟滚动条
2015/06/15 Javascript
JavaScript控制浏览器全屏及各种浏览器全屏模式的方法、属性和事件
2015/12/20 Javascript
Bootstrap树形组件jqTree的简单封装
2016/01/25 Javascript
BOM系列第一篇之定时器setTimeout和setInterval
2016/08/17 Javascript
JavaScript在form表单中使用button按钮实现submit提交方法
2017/01/23 Javascript
[01:07:15]DOTA2-DPC中国联赛 正赛 DLG vs XG BO3 第二场 1月25日
2021/03/11 DOTA
python实现在pickling的时候压缩的方法
2014/09/25 Python
用Python编写一个简单的俄罗斯方块游戏的教程
2015/04/03 Python
快速解决PyCharm无法引用matplotlib的问题
2018/05/24 Python
python 3.7.0 下pillow安装方法
2018/08/27 Python
用xpath获取指定标签下的所有text的实例
2019/01/02 Python
django 信号调度机制详解
2019/07/19 Python
python实现爬虫抓取小说功能示例【抓取金庸小说】
2019/08/09 Python
Python Scrapy框架第一个入门程序示例
2020/02/05 Python
python操作docx写入内容,并控制文本的字体颜色
2020/02/13 Python
Python中私有属性的定义方式
2020/03/05 Python
Python3 mmap内存映射文件示例解析
2020/03/23 Python
tensorflow使用L2 regularization正则化修正overfitting过拟合方式
2020/05/22 Python
python操作链表的示例代码
2020/09/27 Python
国际鲜花速递专家:Floraqueen
2016/11/24 全球购物
HolidayLettings英国:预订最好的度假公寓、别墅和自助式住宿
2019/08/27 全球购物
德国大型箱包和皮具商店:Koffer
2019/10/01 全球购物
Piercing Pagoda官网:耳环、戒指、项链、手链等
2020/09/28 全球购物
企业演讲比赛主持词
2014/03/18 职场文书
年度安全生产目标责任书
2014/07/23 职场文书
贫困证明模板(3篇)
2014/09/16 职场文书
社区低保工作总结2015
2015/07/23 职场文书
《植树问题》教学反思
2016/03/03 职场文书
如何使用CocosCreator对象池
2021/04/14 Javascript