Python 3.7 - asyncio.sleep() 和 time.sleep() [英] Python 3.7 - asyncio.sleep() and time.sleep()

查看:173
本文介绍了Python 3.7 - asyncio.sleep() 和 time.sleep()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我转到 asyncio 页面时,第一个示例是一个 hello world 程序.当我在 python 3.73 上运行它时,我看不出与正常的有什么不同,谁能告诉我有什么不同并举一个不平凡的例子?>

When I go to the asyncio page, the first example is a hello world program. When I run it on python 3.73, I can't see any different from the normal one, can anyone tell me the difference and give a non-trivial example?

In [1]: import asyncio
   ...:
   ...: async def main():
   ...:     print('Hello ...')
   ...:     await asyncio.sleep(5)
   ...:     print('... World!')
   ...:
   ...: # Python 3.7+
   ...: asyncio.run(main())
Hello ...
... World!

In [2]:

In [2]: import time
   ...:
   ...: def main():
   ...:     print('Hello ...')
   ...:     time.sleep(5)
   ...:     print('... World!')
   ...:
   ...: # Python 3.7+
   ...: main()
Hello ...
... World!

我故意将时间从 1 秒增加到 5 秒,希望看到一些特别的东西,但我没有.

I intentionally increase the time from 1s to 5s, hope to see something special but I didn't.

推荐答案

您没有看到任何特别之处,因为您的代码中没有太多异步工作.但是,主要区别在于 time.sleep(5) 是阻塞的,而 asyncio.sleep(5) 是非阻塞的.

You aren't seeing anything special because there's nothing much asynchronous work in your code. However, the main difference is that time.sleep(5) is blocking, and asyncio.sleep(5) is non-blocking.

time.sleep(5)被调用时,它会阻塞整个脚本的执行,它会被搁置,只是冻结,什么都不做.但是当您调用 await asyncio.sleep(5) 时,它会要求事件循环在您的 await 语句完成执行时运行其他内容.

When time.sleep(5) is called, it will block the entire execution of the script and it will be put on hold, just frozen, doing nothing. But when you call await asyncio.sleep(5), it will ask the event loop to run something else while your await statement finishes its execution.

这是一个改进的例子.

import asyncio

async def hello():
    print('Hello ...')
    await asyncio.sleep(5)
    print('... World!')

async def main():
    await asyncio.gather(hello(), hello())

asyncio.run(main())

将输出:

~$ python3.7 async.py
Hello ...
Hello ...
... World!
... World!

您可以看到 await asyncio.sleep(5) 并没有阻止脚本的执行.

You can see that await asyncio.sleep(5) is not blocking the execution of the script.

希望有帮助:)

这篇关于Python 3.7 - asyncio.sleep() 和 time.sleep()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆