@contextmanager
def patch_os_environment(remove=None, **values):
 old_values = {}
 remove = (remove or [])
 for key in remove:
  old_values[key] = os.environ.pop(key)
 for (key, value) in values.iteritems():
  old_values[key] = os.getenv(key)
  os.environ[key] = value
 try:
  (yield)
 finally:
  for (old_key, old_value) in old_values.iteritems():
   if (old_value is None):
    try:
     del os.environ[key]
    except KeyError:
     pass
   else:
    os.environ[old_key] = old_value

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