1# Copyright 2016 The Chromium Authors. All rights reserved. 2# Use of this source code is governed by a BSD-style license that can be 3# found in the LICENSE file. 4 5 6import contextlib 7import shutil 8import tempfile 9 10 11@contextlib.contextmanager 12def NamedTemporaryDirectory(suffix='', prefix='tmp', dir=None): 13 """A context manager that manages a temporary directory. 14 15 This is a context manager version of tempfile.mkdtemp. The arguments to this 16 function are the same as the arguments for that one. 17 18 This can be used to automatically manage the lifetime of a temporary file 19 without maintaining an open file handle on it. Doing so can be useful in 20 scenarios where a parent process calls a child process to create a temporary 21 file and then does something with the resulting file. 22 """ 23 # This uses |dir| as a parameter name for consistency with mkdtemp. 24 # pylint: disable=redefined-builtin 25 26 d = tempfile.mkdtemp(suffix=suffix, prefix=prefix, dir=dir) 27 try: 28 yield d 29 finally: 30 shutil.rmtree(d) 31