对于Python协程中关于asyncio.sleep(1)的困惑?

 暖暖de苹果的马甲 发布于 2022-10-27 16:48

参考教程

官方文档和廖雪峰教程

实例代码

这是一段取自于官方文档的代码,对于这个asyncio.sleep(1)有点不理解,官方文档对于它的描述是"This function is a coroutine."

对于yield from它的用法又是这样解释的:

result = await coroutine or result = yield from coroutine – wait for another coroutine to produce a result (or raise an exception, which will be propagated). The coroutine expression must be a call to another coroutine.

import asyncio
import datetime

@asyncio.coroutine
def display_date(loop):
    end_time = loop.time() + 5.0
    while True:
        print(datetime.datetime.now())
        if (loop.time() + 1.0) >= end_time:
            break
        yield from asyncio.sleep(1)

loop = asyncio.get_event_loop()
# Blocking call which returns when the display_date() coroutine is done
loop.run_until_complete(display_date(loop))
loop.close()

执行结果

2016-12-18 16:27:04.706730
2016-12-18 16:27:05.708139
2016-12-18 16:27:06.709590
2016-12-18 16:27:07.711203
2016-12-18 16:27:08.712784

问题描述

问题一

display_date(loop)本身也是一个协程,asyncio.sleep(1)也是一个协程,请问sleep这个协程是怎么实现的?看到一些教程说yield from asyncio.sleep(1)用来模拟IO任务,请问大神能举一下例子怎么将这个asyncio.sleep(1)模拟程成真正的IO任务吗?也就是说编写一个自己的模拟IO任务的协程,而不是使用抽象的asyncio.sleep(1)。

问题二

对于loop.run_until_complete(display_date(loop))这段代码display_date(loop)返回的结果是什么?

抱歉因为英文不是很好,官方文档看起来有点吃力,尽力了但是问题描述的还是有点乱,如果描述的不够详细,拜托大神在评论区留言一下,我再改进!

补充

In [1]: def reader():
   ...:     for i in range(4):
   ...:         yield i
   ...:         

In [2]: def reader_from(g):
   ...:     yield from g
   ...:   
  
In [3]: wrap = reader_from(reader())

In [4]: wrap
Out[4]: 

In [5]: reader()
Out[5]: 

问题提的没水平,已关闭

2 个回答
    1. asyncio.sleep()其实一看源码就知道了,内部调用了call_at(有点忘了,应该是这个),其实就是一个定时器,在空闲时,问问调度器,"时间到了没?我可以开始了么?"

    2. 协程返回的是一个coroutine(generator)对象,在你cor.send(None)之后才会"返回"一些值

    2022-11-12 01:41 回答
  • 1.模拟io任务的意思是它模拟了处理一些任务所需要的时间,比如我打开一个网址要1秒,那么我就用asyncio.sleep(1)来模拟这一秒的用时而已......

    2.返回的是None啊......它没有显式的规定返回值,所以python的默认返回值返回None

    2022-11-12 01:41 回答
撰写答案
今天,你开发时遇到什么问题呢?
立即提问
热门标签
PHP1.CN | 中国最专业的PHP中文社区 | PNG素材下载 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有