前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Python3.7的新API:asyncio.run()

Python3.7的新API:asyncio.run()

原创
作者头像
杜逸先
发布2018-08-24 13:27:32
12.4K0
发布2018-08-24 13:27:32
举报
文章被收录于专栏:追不上乌龟的兔子

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()方法执行异步函数。一个典型的例子是这样的。

代码语言:txt
复制
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))

运行结果如:

代码语言:txt
复制
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()函数的官方文档是这样子的:

代码语言:txt
复制
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(),上述例子可以改写为:

代码语言:txt
复制
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 删除。

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 传统的asyncio异步事件循环
  • 使用asyncio.run()函数执行异步函数
  • 结语
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档