File: working_directory.py

package info (click to toggle)
chromium-browser 41.0.2272.118-1
  • links: PTS, VCS
  • area: main
  • in suites: jessie-kfreebsd
  • size: 2,189,132 kB
  • sloc: cpp: 9,691,462; ansic: 3,341,451; python: 712,689; asm: 518,779; xml: 208,926; java: 169,820; sh: 119,353; perl: 68,907; makefile: 28,311; yacc: 13,305; objc: 11,385; tcl: 3,186; cs: 2,225; sql: 2,217; lex: 2,215; lisp: 1,349; pascal: 1,256; awk: 407; ruby: 155; sed: 53; php: 14; exp: 11
file content (61 lines) | stat: -rwxr-xr-x 1,682 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
#!/usr/bin/python
# Copyright (c) 2012 The Native Client Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.

"""Classes to create working directories of various sorts."""

import logging
import os
import shutil
import tempfile


class FixedWorkingDirectory(object):
  """Working directory manager to be used with 'with'.

  The context manager does not clean the directory on entry or exit.

  Example uses:
    with WorkingDirectory('mydir', clobber=True) as work_dir:
      ...do stuff in work_dir...
  """

  def __init__(self, work_dir=None, clobber=False):
    """ Constructor.

    Args:
      work_dir: A selected working directory.
    """
    self._work_dir = os.path.abspath(work_dir)
    self._clobber = clobber

  def __enter__(self):
    if self._clobber and os.path.exists(self._work_dir):
      logging.debug('Removing %s...' % self._work_dir)
      shutil.rmtree(self._work_dir)
    if not os.path.exists(self._work_dir):
      logging.debug('Creating %s...' % self._work_dir)
      os.mkdir(self._work_dir)
    return self._work_dir

  def __exit__(self, _type, _value, _trackback):
    pass


class TemporaryWorkingDirectory(object):
  """Working directory manager to be used with 'with'.

  The manager creates a temporary working directory and cleans it
  up at the end.

  Example uses:
    with TemporaryWorkingDirectory() as work_dir:
      ...do stuff in work_dir...
  """
  def __enter__(self):
    self._work_dir = tempfile.mkdtemp(prefix='workdir', suffix='.tmp')
    return self._work_dir

  def __exit__(self, _type, _value, _trackback):
    shutil.rmtree(self._work_dir)