当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


Python contextlib.ExitStack.pop_all用法及代码示例


用法:

pop_all()

将回调堆栈转移到新的 ExitStack 实例并返回它。此操作不会调用回调 - 相反,现在将在新堆栈关闭时调用它们(在 with 语句的末尾显式或隐式地)。

例如,一组文件可以作为 “all or nothing” 操作打开,如下所示:

with ExitStack() as stack:
    files = [stack.enter_context(open(fname)) for fname in filenames]
    # Hold onto the close method, but don't call it yet.
    close_files = stack.pop_all().close
    # If opening any file fails, all previously opened files will be
    # closed automatically. If all files are opened successfully,
    # they will remain open even after the with statement ends.
    # close_files() can then be invoked explicitly to close them all.

相关用法


注:本文由纯净天空筛选整理自python.org大神的英文原创作品 contextlib.ExitStack.pop_all。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。