Package logilab :: Package common :: Module contexts
[frames] | no frames]

Source Code for Module logilab.common.contexts

 1  # copyright 2003-2010 LOGILAB S.A. (Paris, FRANCE), all rights reserved. 
 2  # contact http://www.logilab.fr/ -- mailto:contact@logilab.fr 
 3  # 
 4  # This file is part of logilab-common. 
 5  # 
 6  # logilab-common is free software: you can redistribute it and/or modify it under 
 7  # the terms of the GNU Lesser General Public License as published by the Free 
 8  # Software Foundation, either version 2.1 of the License, or (at your option) any 
 9  # later version. 
10  # 
11  # logilab-common is distributed in the hope that it will be useful, but WITHOUT 
12  # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS 
13  # FOR A PARTICULAR PURPOSE.  See the GNU Lesser General Public License for more 
14  # details. 
15  # 
16  # You should have received a copy of the GNU Lesser General Public License along 
17  # with logilab-common.  If not, see <http://www.gnu.org/licenses/>. 
18  """A few useful context managers 
19   
20   
21   
22   
23  """ 
24  __docformat__ = "restructuredtext en" 
25   
26  import sys 
27   
28  if sys.version_info < (2, 5): 
29      raise ImportError("python >= 2.5 is required to import logilab.common.contexts") 
30   
31  import os 
32  import tempfile 
33  import shutil 
34   
35 -class tempdir(object):
36
37 - def __enter__(self):
38 self.path = tempfile.mkdtemp() 39 return self.path
40
41 - def __exit__(self, exctype, value, traceback):
42 # rmtree in all cases 43 shutil.rmtree(self.path) 44 return traceback is None
45 46
47 -class pushd(object):
48 - def __init__(self, directory):
49 self.directory = directory
50
51 - def __enter__(self):
52 self.cwd = os.getcwd() 53 os.chdir(self.directory) 54 return self.directory
55
56 - def __exit__(self, exctype, value, traceback):
57 os.chdir(self.cwd)
58