Python3.7的正式版本已经发布有一段时间了,出了内置的breakpoint()
断点函数,颇受争议的dataclass,自定义模块里的__getattr__()
和__dir__()
魔法方法等新特性外以及一些底层的改进外,还添加了一些新的api。其中我个人比较喜欢的一个新API是asyncio.run()
方法,可以省去显式的定义事件循环的步骤。
在Python3.7以前的版本,调用异步函数前要先调用asyncio.get_event_loop()
函数获取事件循环loop对象,然后通过不同的策略调用loop.run_forever()
方法或者loop.run_until_complete()
方法执行异步函数。一个典型的例子是这样的。
import asyncio
import random
import datetime
async def wait_and_echo(content):
wait = random.randint(0, 10)
print(f'print {content} after {wait} seconds')
await asyncio.sleep(wait)
print(f'{content} printed at {datetime.datetime.utcnow().strftime("%H:%M:%S ")}')
async def main():
await asyncio.gather(*[wait_and_echo(x) for x in range(10)])
loop = asyncio.get_event_loop()
tasks = [wait_and_echo(x) for x in range(10)]
loop.run_until_complete(asyncio.gather(*tasks))
运行结果如:
print 0 after 9 seconds
print 1 after 0 seconds
print 2 after 7 seconds
print 3 after 2 seconds
print 4 after 8 seconds
print 5 after 3 seconds
print 6 after 2 seconds
print 7 after 9 seconds
print 8 after 1 seconds
print 9 after 1 seconds
1 printed at 05:15:26
8 printed at 05:15:27
9 printed at 05:15:27
6 printed at 05:15:28
3 printed at 05:15:28
5 printed at 05:15:29
2 printed at 05:15:33
4 printed at 05:15:34
0 printed at 05:15:35
7 printed at 05:15:35
asyncio.run()
函数的官方文档是这样子的:
Signature: asyncio.run(main, *, debug=False)
Docstring:
Run a coroutine.
This function runs the passed coroutine, taking care of
managing the asyncio event loop and finalizing asynchronous
generators.
This function cannot be called when another asyncio event loop is
running in the same thread.
If debug is True, the event loop will be run in debug mode.
This function always creates a new event loop and closes it at the end.
It should be used as a main entry point for asyncio programs, and should
ideally only be called once.
Example:
async def main():
await asyncio.sleep(1)
print('hello')
asyncio.run(main())
File: c:\users\pc\appdata\local\programs\python\python37\lib\asyncio\runners.py
Type: function
使用Python3.7中的新APIasyncio.run()
,上述例子可以改写为:
import asyncio
import random
import datetime
async def wait_and_echo(content):
wait = random.randint(0, 10)
print(f'print {content} after {wait} seconds')
await asyncio.sleep(wait)
print(f'{content} printed at {datetime.datetime.utcnow().strftime("%H:%M:%S ")}')
async def main():
await asyncio.gather(*[wait_and_echo(x) for x in range(10)])
asyncio.run(main())
运行结果并没有差异。
新版本,新用法。还是要多学习和实践。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。