Handy functions to save and restore the arcpy environment

Blog Post created by curtvprice Champion on May 5, 2015

I have run across the need to save and restore the arcpy environment. For example, a function (or a tool packaged in a function) may alter the environment and it would be nice to have an easy way to set it back at the end.


Arcpy provides the functions SaveSettings and LoadSettings, but they require that an XML file be created. I was having problems with these functions and had a epiphany that this could be more easily done by combining the ListEnvironments function and a Python dictionary.




def SaveEnv():
    """Save selected arcpy environments as dict"""
    env_dict = {}
    for e in arcpy.ListEnvironments():
        if e not in ["scratchGDB", "scratchFolder", "packageWorkspace"]:
            env_dict[e] = arcpy.env[e]
    return env_dict

def LoadEnv(env_dict, display=False):
    """Load selected arcpy environments from dict"""
    for e in env_dict.keys():
        arcpy.env[e] = env_dict[e]
        if display:
            arcpy.AddMessage("{0:<30}: {1}".format(e, env_dict[e]))
            print("{0:<30}: {1}".format(e, env_dict[e]))


Here's how I am using these functions to keep GISProc from messing up environment when called:


def GISProc(arg1, arg2):
    envs = SaveEnv()
        # Tool goes here ...
        arcpy.env.extent = ...
        arcpy.env.cellSize = ...