• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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
5import contextlib
6import os
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
32
33@contextlib.contextmanager
34def NamedTemporaryFile(mode='w+b', suffix='', prefix='tmp'):
35  """A conext manager to hold a named temporary file.
36
37  It's similar to Python's tempfile.NamedTemporaryFile except:
38  - The file is _not_ deleted when you close the temporary file handle, so you
39    can close it and then use the name of the file to re-open it later.
40  - The file *is* always deleted when exiting the context managed code.
41  """
42  with NamedTemporaryDirectory() as temp_dir:
43    yield tempfile.NamedTemporaryFile(
44        mode=mode, suffix=suffix, prefix=prefix, dir=temp_dir, delete=False)
45
46
47@contextlib.contextmanager
48def TemporaryFileName(prefix='tmp', suffix=''):
49  """A context manager to just get the path to a file that does not exist.
50
51  The parent directory of the file is a newly clreated temporary directory,
52  and the name of the file is just `prefix + suffix`. The file istelf is not
53  created, you are in fact guaranteed that it does not exit.
54
55  The entire parent directory, possibly including the named temporary file and
56  any sibling files, is entirely deleted when exiting the context managed code.
57  """
58  with NamedTemporaryDirectory() as temp_dir:
59    yield os.path.join(temp_dir, prefix + suffix)
60