Python3.7的新的新API:asyncio.run()
Python3.7的新的新API:asyncio.run()
Python3.7的正式版本已经发布有一段时间了,出了内置的breakpoint()断点函数,颇受争议的dataclass,自定义模块里
的__getattr__()和__dir__()魔法方法等新特性外以及一些底层的改进外,还添加了一些新的api。其中我个人比较喜欢的一个新API
是asyncio.run()方法,可以省去显式的定义事件循环的步骤。
传统的传统的asyncio异步事件循环异步事件循环
在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()函数执行异步函数函数执行异步函数
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
评论0
最新资源