Created
June 25, 2016 11:24
-
-
Save blueskyjunkie/af8e1d7db6af3418ca9d96277219ed34 to your computer and use it in GitHub Desktop.
Use a 'with' block to temporarily change the working directory.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# | |
# 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