Skip to content

Instantly share code, notes, and snippets.

@blueskyjunkie
Created June 25, 2016 11:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save blueskyjunkie/af8e1d7db6af3418ca9d96277219ed34 to your computer and use it in GitHub Desktop.
Save blueskyjunkie/af8e1d7db6af3418ca9d96277219ed34 to your computer and use it in GitHub Desktop.
Use a 'with' block to temporarily change the working directory.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
import logging
import os
log = logging.getLogger( __name__ )
class ChangeDir( ) :
'''
Using "with ChangeDir( path ):" the enclosed code uses the specified path as the working directory. On exiting the
'with' block, the working directory is restored to that before entering the 'with' block.
'''
def __init__( self, newPath ) :
self._newPath = newPath
self._savedPath = os.getcwd( )
log.info( 'Saving path, ' + repr( self._savedPath ) )
def __enter__( self ) :
# Change to the new directory
os.chdir( self._newPath )
log.info( 'Changing to path, ' + repr( self._newPath ) )
return self._newPath
def __exit__( self, exc_type, exc_value, traceback ) :
if exc_type is not None :
# An error occured.
log.error( exc_type, exc_value, traceback )
return False
# Restore the path stored at instantiation
log.info( 'Restoring original saved path, ' + repr( self._savedPath ) )
os.chdir( self._savedPath )
return self
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment