Python 3.7 - asyncio.sleep() 和 time.sleep()
Python 3.7 - asyncio.sleep() and time.sleep()
当我转到 asyncio
页面时,第一个示例是一个 hello world 程序。当我 运行 它在 python 3.73
上时,我看不出与正常的有什么不同,谁能告诉我区别并举一个重要的例子?
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 秒,希望看到一些特别的东西但我没有。
您没有看到任何特别之处,因为您的代码中没有太多异步工作。但是,主要区别在于 time.sleep(5)
是阻塞,而 asyncio.sleep(5)
是 non-blocking。
当time.sleep(5)
被调用时,它会阻塞整个脚本的执行,它会被搁置,只是冻结,什么都不做。但是当你调用 await asyncio.sleep(5)
时,它会在你的 await 语句完成执行时要求事件循环 运行 其他东西。
这是一个改进的例子。
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)
没有阻塞脚本的执行。
希望对您有所帮助:)
当我转到 asyncio
页面时,第一个示例是一个 hello world 程序。当我 运行 它在 python 3.73
上时,我看不出与正常的有什么不同,谁能告诉我区别并举一个重要的例子?
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 秒,希望看到一些特别的东西但我没有。
您没有看到任何特别之处,因为您的代码中没有太多异步工作。但是,主要区别在于 time.sleep(5)
是阻塞,而 asyncio.sleep(5)
是 non-blocking。
当time.sleep(5)
被调用时,它会阻塞整个脚本的执行,它会被搁置,只是冻结,什么都不做。但是当你调用 await asyncio.sleep(5)
时,它会在你的 await 语句完成执行时要求事件循环 运行 其他东西。
这是一个改进的例子。
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)
没有阻塞脚本的执行。
希望对您有所帮助:)