Skip to content

Instantly share code, notes, and snippets.

@phobson
Last active February 10, 2016 18:01
Show Gist options
  • Save phobson/b3078602db48fbe5bd49 to your computer and use it in GitHub Desktop.
Save phobson/b3078602db48fbe5bd49 to your computer and use it in GitHub Desktop.
## How I think you should do it
### this lives tucked away somewhere
import arcpy
class Extension(object):
def __init__(self, name):
self.name = name
def __enter__(self):
if arcpy.CheckExtension(self.name) == "Available":
arcpy.CheckOutExtension(self.name)
else:
raise ValueError("%s license isn't available" % self.name)
def __exit__(self, *args):
arcpy.CheckInExtension(self.name)
class OverwriteState(object):
def __init__(self, overwrite):
self.orig_state = arcpy.env.overwriteOutput
self.new_state = bool(overwrite)
def __enter__(self, *args, **kwargs):
arcpy.env.overwriteOutput = self.new_state
def __exit__(self, *args, **kwargs):
arcpy.env.overwriteOutput = self.orig_state
class WorkSpace(object):
def __init__(self, path):
self.orig_workspace = arcpy.env.workspace
self.new_workspace = path
def __enter__(self, *args, **kwargs):
arcpy.env.workspace = self.new_workspace
def __exit__(self, *args, **kwargs):
arcpy.env.workspace = self.orig_workspace
### then you can just do this:
with Extension("3D"), OverwriteState(True), Workspace("c:/GrosMorne"):
arcpy.HillShade_3d("WesternBrook", "wbrook_hill", 300)
arcpy.Aspect_3d("WesternBrook", "wbrook_aspect")
#---------------------------------------------------------------
## This is how Esri recommends you to do it every. single. time.
import arcpy
class LicenseError(Exception):
pass
try:
if arcpy.CheckExtension("3D") == "Available":
arcpy.CheckOutExtension("3D")
else:
# raise a custom exception
raise LicenseError
arcpy.env.workspace = "c:/GrosMorne"
arcpy.HillShade_3d("WesternBrook", "wbrook_hill", 300)
arcpy.Aspect_3d("WesternBrook", "wbrook_aspect")
arcpy.CheckInExtension("3D")
except LicenseError:
print("3D Analyst license is unavailable")
except arcpy.ExecuteError:
print(arcpy.GetMessages(2))
from contextlib improt contextmanager
import arcpy
@contextmanager
def Extension(name):
""" Context manager to facilitate the use of ArcGIS extensions
Inside the context manager, the extension will be checked out. Once
the interpreter leaves the code block by any means (e.g., successful
execution, raised exception) the extension will be checked back in.
Examples
--------
>>> import propagator, arcpy
>>> with propagator.utils.Extension("spatial"):
... arcpy.sa.Hillshade("C:/data/dem.tif")
"""
if arcpy.CheckExtension(name) == u"Available":
status = arcpy.CheckOutExtension(name)
yield status
else:
raise RuntimeError("%s license isn't available" % name)
arcpy.CheckInExtension(name)
@contextmanager
def OverwriteState(state):
""" Context manager to temporarily set the ``overwriteOutput``
environment variable.
Inside the context manager, the ``arcpy.env.overwriteOutput`` will
be set to the given value. Once the interpreter leaves the code
block by any means (e.g., successful execution, raised exception),
``arcpy.env.overwriteOutput`` will reset to its original value.
Parameters
----------
path : str
Path to the directory that will be set as the current workspace.
Examples
--------
>>> from propagator import utils
>>> with utils.OverwriteState(False):
... # some operation that should fail if output already exists
"""
orig_state = arcpy.env.overwriteOutput
arcpy.env.overwriteOutput = bool(state)
yield state
arcpy.env.overwriteOutput = orig_state
@contextmanager
def WorkSpace(path):
""" Context manager to temporarily set the ``workspace``
environment variable.
Inside the context manager, the `arcpy.env.workspace`_ will
be set to the given value. Once the interpreter leaves the code
block by any means (e.g., successful execution, raised exception),
`arcpy.env.workspace`_ will reset to its original value.
.. _arcpy.env.workspace: http://goo.gl/0NpeFN
Parameters
----------
path : str
Path to the directory that will be set as the current workspace.
Examples
--------
>>> import propagator
>>> with propagator.utils.OverwriteState(False):
... # some operation that should fail if output already exists
"""
orig_workspace = arcpy.env.workspace
arcpy.env.workspace = path
yield path
arcpy.env.workspace = orig_workspace
@phobson
Copy link
Author

phobson commented Aug 18, 2015

@jasonbot Does it really matter? What's the benefit of that?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment