#NEWLINE# @ contextmanager #NEWLINE# def patch_os_environment( remove = None , **values ) : #NEWLINE# #INDENT# '\n    Context manager for patching the operating system environment.\n    ' #NEWLINE# old_values = { #NEWLINE# #INDENT# #NEWLINE# #UNINDENT# } #NEWLINE# remove = ( remove or [ ] ) #NEWLINE# for key in remove : #NEWLINE# #INDENT# old_values [ key ] = os . environ . pop ( key ) #NEWLINE# #UNINDENT# for ( key , value ) in values . iteritems ( ) : #NEWLINE# #INDENT# old_values [ key ] = os . getenv ( key ) #NEWLINE# os . environ [ key ] = value #NEWLINE# #UNINDENT# try : #NEWLINE# #INDENT# ( yield ) #NEWLINE# #UNINDENT# finally : #NEWLINE# #INDENT# for ( old_key , old_value ) in old_values . iteritems ( ) : #NEWLINE# #INDENT# if ( old_values is None ) : #NEWLINE# #INDENT# try : #NEWLINE# #INDENT# del os . environ [ key ] #NEWLINE# #UNINDENT# except KeyError : #NEWLINE# #INDENT# pass #NEWLINE# #UNINDENT# #UNINDENT# else : #NEWLINE# #INDENT# os . environ [ old_key ] = old_value