當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


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。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。