美文网首页
关于async with 表达式

关于async with 表达式

作者: 猪猪一号 | 来源:发表于2020-04-06 22:22 被阅读0次
  • 与 with 中的上下文管理器需要定义两个方法 enter() 和 exit() 一样,异步上下文管理器同样也需要实现 aenter() 和 aexit() 方法。
  • async with 异步上下文管理器同样只能在 协程函数 中使用,否则会报语法错误 ( SyntaxError )。
  • 与普通上下文管理器相比,异步上下文管理器能够在其进入 enter() 和退出方法 exit() 中暂停执行
  • 详细的理解可参照普通的的with上下文管理器:
    Python深入02 上下文管理器

示例代码

import asyncio

async def log(some_thing):
    print(some_thing)

class AsyncContextManager:
    async def __aenter__(self):
        await log('entering context')
        return "返回值做为c的值"

    async def __aexit__(self, exc_type, exc, tb):
        await log('exiting context')


async def run_async_with():

    async with AsyncContextManager() as c:
        print("使用 async with 来管理异步上下文")
        print(c)

loop = asyncio.get_event_loop()
loop.run_until_complete(run_async_with())
loop.close()

输出

entering context
使用 async with 来管理异步上下文
返回值做为c的值
exiting context

相关文章

网友评论

      本文标题:关于async with 表达式

      本文链接:https://www.haomeiwen.com/subject/dzoiphtx.html