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.
Enjoy!
def SaveEnv(): """Save selected arcpy environments as dict""" env_dict = {} for e in arcpy.ListEnvironments(): if e not in ["scratchGDB", "scratchFolder", "packageWorkspace"]: env_dict= arcpy.env return env_dict def LoadEnv(env_dict, display=False): """Load selected arcpy environments from dict""" for e in env_dict.keys(): arcpy.env= env_dict if display: arcpy.AddMessage("{0:<30}: {1}".format(e, env_dict)) print("{0:<30}: {1}".format(e, env_dict))
Here's how I am using these functions to keep GISProc from messing up environment when called:
def GISProc(arg1, arg2): envs = SaveEnv() try: # Tool goes here ... arcpy.env.extent = ... arcpy.env.cellSize = ... except: ... finally: LoadEnv(envs)
You must be a registered user to add a comment. If you've already registered, sign in. Otherwise, register and sign in.