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

本文通过一个具体的示例代码,解析了Python中asyncio模块的使用方法,并针对asyncio.sleep()函数进行了深入探讨。文章解答了两个核心问题:如何实现自定义的IO模拟协程及display_date(loop)协程的运行机制。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

参考教程

实例代码

这是一段取自于官方文档的代码,对于这个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]:

问题提的没水平,已关闭

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值