在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实现颜色空间转换程序(Tkinter)
Dec 31 Python
Python使用functools模块中的partial函数生成偏函数
Jul 02 Python
Python 常用的安装Module方式汇总
May 06 Python
Python 机器学习库 NumPy入门教程
Apr 19 Python
Python3多线程基础知识点
Feb 19 Python
Django框架使用内置方法实现登录功能详解
Jun 12 Python
Python split() 函数拆分字符串将字符串转化为列的方法
Jul 16 Python
numpy按列连接两个维数不同的数组方式
Dec 06 Python
django框架F&Q 聚合与分组操作示例
Dec 12 Python
python中导入 train_test_split提示错误的解决
Jun 19 Python
Python中的With语句的使用及原理
Jul 29 Python
能让Python提速超40倍的神器Cython详解
Jun 24 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
apache2.2.4+mysql5.0.77+php5.2.8安装精简
2009/04/29 PHP
PHP中使用Imagick读取pdf并生成png缩略图实例
2015/01/21 PHP
Symfony2针对输入时间进行查询的方法分析
2017/06/28 PHP
Yii框架函数简单用法分析
2019/09/09 PHP
php经典趣味算法实例代码
2020/01/21 PHP
[原创]图片分页查看
2006/08/28 Javascript
动态刷新 dorado树的js代码
2009/06/12 Javascript
javascript dom代码应用 简单的相册[firefox only]
2010/06/12 Javascript
jQuery基本选择器选择元素使用介绍
2013/04/18 Javascript
基于JavaScript 下namespace 功能的简单分析
2013/07/05 Javascript
jquery基础教程之deferred对象使用方法
2014/01/22 Javascript
中止javascript执行的方法
2014/02/14 Javascript
jQuery结合AJAX之在页面滚动时从服务器加载数据
2015/06/30 Javascript
基于jQuery实现的仿百度首页滑动选项卡效果代码
2015/11/16 Javascript
jQuery验证表单格式的使用方法
2017/01/10 Javascript
AngularJS的$location使用方法详解
2017/10/19 Javascript
实现div滚动条默认最底部以及默认最右边的示例代码
2017/11/15 Javascript
jQuery+Ajax+js实现请求json格式数据并渲染到html页面操作示例
2020/06/02 jQuery
JS forEach跳出循环2种实现方法
2020/06/24 Javascript
python备份文件的脚本
2008/08/11 Python
分享6个隐藏的python功能
2017/12/07 Python
Python中的探索性数据分析(功能式)
2017/12/22 Python
Python运维之获取系统CPU信息的实现方法
2018/06/11 Python
python使用magic模块进行文件类型识别方法
2018/12/08 Python
Python 2/3下处理cjk编码的zip文件的方法
2019/04/26 Python
Python requests设置代理的方法步骤
2020/02/23 Python
Selenium执行完毕未关闭chromedriver/geckodriver进程的解决办法(java版+python版)
2020/12/07 Python
英国最大的在线快递公司之一:ParcelHero
2019/11/04 全球购物
Why do we need Unit test
2013/01/03 面试题
学员自我鉴定
2014/03/19 职场文书
电子商务专业毕业生求职信
2014/06/12 职场文书
教师业务学习材料
2014/12/16 职场文书
敬业奉献模范事迹材料
2014/12/24 职场文书
2015年先进个人自荐书
2015/03/24 职场文书
2016教师政治学习心得体会
2016/01/23 职场文书
muduo TcpServer模块源码分析
2022/04/26 Redis