• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# Copyright 2015 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"""Miscellaneous utility functions."""
6
7import contextlib
8import shutil
9import sys
10import tempfile
11
12
13# We're trying to be compatible with Python3 tempfile.TemporaryDirectory
14# context manager here. And they used 'dir' as a keyword argument.
15# pylint: disable=redefined-builtin
16@contextlib.contextmanager
17def temporary_directory(suffix="", prefix="tmp", dir=None,
18                        keep_directory=False):
19  """Create and return a temporary directory.  This has the same
20  behavior as mkdtemp but can be used as a context manager.  For
21  example:
22
23    with temporary_directory() as tmpdir:
24      ...
25
26  Upon exiting the context, the directory and everything contained
27  in it are removed.
28
29  Args:
30    suffix, prefix, dir: same arguments as for tempfile.mkdtemp.
31    keep_directory (bool): if True, do not delete the temporary directory
32      when exiting. Useful for debugging.
33
34  Returns:
35    tempdir (str): full path to the temporary directory.
36  """
37  tempdir = None  # Handle mkdtemp raising an exception
38  try:
39    tempdir = tempfile.mkdtemp(suffix, prefix, dir)
40    yield tempdir
41
42  finally:
43    if tempdir and not keep_directory:  # pragma: no branch
44      try:
45        # TODO(pgervais,496347) Make this work reliably on Windows.
46        shutil.rmtree(tempdir, ignore_errors=True)
47      except OSError as ex:  # pragma: no cover
48        print >> sys.stderr, (
49          "ERROR: {!r} while cleaning up {!r}".format(ex, tempdir))
50