# TestFastVisibilityByCircle_SingleInput.py # Description: Test Publishable Tasks Toolbox > Fast Visibility By Circle with single input circle # Requirements: ArcGIS Desktop Standard with Spatial Analyst Extension # ---------------------------------------------------------------------------- import arcpy import sys import traceback import TestUtilities import os class LicenseError(Exception): pass try: if arcpy.CheckExtension("Spatial") == "Available": arcpy.CheckOutExtension("Spatial") else: raise LicenseError arcpy.ImportToolbox(TestUtilities.toolbox) arcpy.env.overwriteOutput = True inputCircle = os.path.join(TestUtilities.inputGDB, "FVBC_InputCircle") inputHeightAboveSurface = 5.0 inputElevationURL = TestUtilities.inputElevationURL psOutput = os.path.join(TestUtilities.outputGDB, "FVBCircle_1_vshed") #Testing Path Slope arcpy.AddMessage("Starting Test: Fast Visibility By Circle - Single input circle") arcpy.FastVisibilityByCircle_pubtask(inputCircle, inputHeightAboveSurface, inputElevationURL,psOutput)
def set_value(input_source, no_flood_value, flood_elevation_value, output_raster, debug): try: # Get Attributes from User if debug == 0: # script variables aprx = arcpy.mp.ArcGISProject("CURRENT") home_directory = aprx.homeFolder tiff_directory = home_directory + "\\Tiffs" tin_directory = home_directory + "\\Tins" scripts_directory = aprx.homeFolder + "\\Scripts" rule_directory = aprx.homeFolder + "\\rule_packages" log_directory = aprx.homeFolder + "\\Logs" layer_directory = home_directory + "\\layer_files" project_ws = aprx.defaultGeodatabase enableLogging = True DeleteIntermediateData = True verbose = 0 in_memory_switch = True else: # debug input_source = r'D:\Gert\Work\Esri\Solutions\3DFloodImpact\work2.1\3DFloodImpact\3DFloodImpact.gdb\c2ft_inundation_Clip' output_raster = r'D:\Gert\Work\Esri\Solutions\3DFloodImpact\work2.1\3DFloodImpact\Testing.gdb\RasterValue' no_flood_value = "0" # value or "NoData" flood_elevation_value = 8 home_directory = r'D:\Gert\Work\Esri\Solutions\3DFloodImpact\work2.1\3DFloodImpact' log_directory = home_directory + "\\Logs" layer_directory = home_directory + "\\LayerFiles" project_ws = home_directory + "\\Testing.gdb" enableLogging = False DeleteIntermediateData = True verbose = 1 in_memory_switch = False scratch_ws = common_lib.create_gdb(home_directory, "Intermediate.gdb") arcpy.env.workspace = scratch_ws arcpy.env.overwriteOutput = True flood_elevation_value = float(re.sub("[,.]", ".", flood_elevation_value)) common_lib.set_up_logging(log_directory, TOOLNAME) start_time = time.clock() if arcpy.CheckExtension("3D") == "Available": arcpy.CheckOutExtension("3D") if arcpy.CheckExtension("Spatial") == "Available": arcpy.CheckOutExtension("Spatial") arcpy.AddMessage("Processing input source: " + common_lib.get_name_from_feature_class(input_source)) # use numeric value for determining non flooded areas: set these values to NoData. We need NoData for clippng later on if no_flood_value != "NoData": if common_lib.is_number(no_flood_value): msg_body = create_msg_body( "Setting no flood value: " + no_flood_value + " to NoData in copy of " + common_lib.get_name_from_feature_class( input_source) + "...", 0, 0) msg(msg_body) null_for_no_flooded_areas_raster = os.path.join(scratch_ws, "null_for_flooded") if arcpy.Exists(null_for_no_flooded_areas_raster): arcpy.Delete_management(null_for_no_flooded_areas_raster) whereClause = "VALUE = " + no_flood_value # Execute SetNull outSetNull_temp = arcpy.sa.SetNull(input_source, input_source, whereClause) outSetNull_temp.save(null_for_no_flooded_areas_raster) input_source = null_for_no_flooded_areas_raster else: raise ValueError # check where there is IsNull and set the con values is_Null = os.path.join(scratch_ws, "is_Null") if arcpy.Exists(is_Null): arcpy.Delete_management(is_Null) is_Null_raster = arcpy.sa.IsNull(input_source) is_Null_raster.save(is_Null) # Con if arcpy.Exists(output_raster): arcpy.Delete_management(output_raster) temp_con_raster = arcpy.sa.Con(is_Null, input_source, flood_elevation_value) temp_con_raster.save(output_raster) msg_body = create_msg_body( "Setting flood elevation value to: " + str(flood_elevation_value) + " in " + common_lib.get_name_from_feature_class(output_raster) + "...", 0, 0) msg(msg_body) end_time = time.clock() msg_body = create_msg_body("Set Flood Elevation Value for Raster completed successfully.", start_time, end_time) arcpy.ClearWorkspaceCache_management() return output_raster else: raise LicenseErrorSpatial else: raise LicenseError3D arcpy.ClearWorkspaceCache_management() msg(msg_body) except NotProjected: print("Input data needs to be in a projected coordinate system. Exiting...") arcpy.AddError("Input data needs to be in a projected coordinate system. Exiting...") except NoLayerFile: print("Can't find Layer file. Exiting...") arcpy.AddError("Can't find Layer file. Exiting...") except LicenseError3D: print("3D Analyst license is unavailable") arcpy.AddError("3D Analyst license is unavailable") except LicenseErrorSpatial: print("Spatial Analyst license is unavailable") arcpy.AddError("Spatial Analyst license is unavailable") except NoNoDataError: print("Input raster does not have NODATA values") arcpy.AddError("Input raster does not have NODATA values") except NoUnits: print("No units detected on input data") arcpy.AddError("No units detected on input data") except NoPolygons: print("Input data can only be polygon features or raster datasets.") arcpy.AddError("Input data can only be polygon features or raster datasets.") except ValueError: print("Input no flood value is not a number.") arcpy.AddError("Input no flood value is not a number.") except arcpy.ExecuteError: line, filename, synerror = trace() msg("Error on %s" % line, ERROR) msg("Error in file name: %s" % filename, ERROR) msg("With error message: %s" % synerror, ERROR) msg("ArcPy Error Message: %s" % arcpy.GetMessages(2), ERROR) except FunctionError as f_e: messages = f_e.args[0] msg("Error in function: %s" % messages["function"], ERROR) msg("Error on %s" % messages["line"], ERROR) msg("Error in file name: %s" % messages["filename"], ERROR) msg("With error message: %s" % messages["synerror"], ERROR) msg("ArcPy Error Message: %s" % messages["arc"], ERROR) except: line, filename, synerror = trace() msg("Error on %s" % line, ERROR) msg("Error in file name: %s" % filename, ERROR) msg("with error message: %s" % synerror, ERROR) finally: arcpy.CheckInExtension("3D") arcpy.CheckInExtension("Spatial")
def processLakes(directory): #Get licensed if arcpy.CheckExtension("Spatial"): arcpy.CheckOutExtension("Spatial") else: print "No SA licence" exit # Load the environment env.workspace = "C:/Users/hengstam/Desktop/Research/hengst_env" arcpy.env.overwriteOutput = True files = glob(env.workspace + '/' + directory + '/*.shp') for ogshapes in files: # Our file to be processed ogshapes = ogshapes[len(env.workspace) + 1:] name = ogshapes[len(directory) + 1:] shapes = 'processed_polygons/' + name # Copy it over print "Processing " + ogshapes + " as " + shapes + "..." arcpy.CopyFeatures_management(ogshapes, shapes) # Get the date and location date = int(name[17:24]) loc = (int(name[10:12]), int(name[13:15])) print date, loc ################################### ## Calculate area and get centroids print "Detailing shapefiles..." # Add fields arcpy.AddField_management(shapes, "area", "DOUBLE") arcpy.AddField_management(shapes, "centr_x", "DOUBLE") arcpy.AddField_management(shapes, "centr_y", "DOUBLE") arcpy.AddField_management(shapes, "lake_id", "STRING") arcpy.AddField_management(shapes, "date", "SHORT") arcpy.AddField_management(shapes, "loc", "SHORT") # Build a cursor to set our new fields cursor = arcpy.da.UpdateCursor(shapes, [ "SHAPE@AREA", "SHAPE@TRUECENTROID", "area", "centr_x", "centr_y", "date", "loc" ]) # Start summing area areaTotal = 0 # Work through all shapes in the feature class for row in cursor: # Running total of area areaTotal = row[0] + areaTotal # Write area value row[2] = row[0] # Write centroid values row[3] = row[1][0] row[4] = row[1][1] # Write date and location row[5] = date row[6] = loc # Save it cursor.updateRow(row) # Clean up cursor objects del row, cursor print "Shapefiles successfully detailed." ################################################ ## Only save large polygons (more than 0.1 km^2) print "Removing small polygons..." arcpy.MakeFeatureLayer_management(shapes, "shapes_lyr") arcpy.SelectLayerByAttribute_management("shapes_lyr", "NEW_SELECTION", "area < 500000") arcpy.DeleteFeatures_management("shapes_lyr") print "Small polygons successfully removed." ########################### ## Name the remaining lakes print "Naming lakes..." # Make a cursor to update the stuff cursor = arcpy.da.UpdateCursor(shapes, ["SHAPE@TRUECENTROID", "lake_id"]) # n is used to count the number of lakes, which is displayed at the end of this script. n = 0 # Go through all lakes in the feature class for row in cursor: # Counting works like this n += 1 # Make hash m = hashlib.sha224() # Use centroid to mutate hash m.update(str(row[0][0])) m.update(str(row[0][1])) # Save it row[1] = m.hexdigest() cursor.updateRow(row) # Clean up cursor objects del cursor # IO print "success! " + str(n) + " lakes found and named." print str(areaTotal) + "m^2 total lake area."
#Gina Fonseca #Chapter 5 Challenge Problem 4 import arcpy #Extension codes "3D" "Spatial" " Network" #Gina Fonseca #Chapter 5 Challenge 04 from arcpy import env env.worskapce = "C:/EsriPress/PythonData/Exercise05" S = "" D = "" N = "" if arcpy.CheckExtension( "Spatial") == "Available": #this one checks for spatial S = "Spatial Analyst" if arcpy.CheckExtension("3D") == "Available": #this statement checks for 3D D = "3D Analyst" if arcpy.CheckExtension( "Network") == "Available": #this statemnent checks for network N = " Network Analyst" print "The following license have been checked and are available: " + S + N + D
# EvcLayerSolver.py # Author: Kaveh Shahabi # Date: Nov 13, 2014 # Usage: EvcLayerSolver.py <Workspace> <Layer_File_Name> # Description: Solves all networtk layers within a layer file and saves the result # The workspace is where the network dataset exist. # --------------------------------------------------------------------------- # Import arcpy module import arcpy import sys arcpy.env.workspace = arcpy.GetParameterAsText(0) arcpy.SetParameter(2, False) # Check out any necessary licenses if arcpy.CheckExtension("Network") == "Available": arcpy.CheckOutExtension("Network") else: arcpy.AddMessage("Network Analyst Extension Is Not Available") print "Network Analyst Is Not Available" sys.exit(0) # Script arguments Layer_Location = arcpy.GetParameterAsText(1) if Layer_Location == '#' or not Layer_Location: raise ValueError("layer location is missing") # load layer file and loop over all network layers lyrFile = arcpy.mapping.Layer(Layer_Location) for lyr in arcpy.mapping.ListLayers(lyrFile): desc = arcpy.Describe(Layer_Location + "\\" + lyr.longName)
""" __author__ = [ "Daniel Jensen, [email protected]", "Jeffry Ely, [email protected]", "Quinten Geddes" ] # local imports from .atsat_bright_temp import * from .cloud_mask import * from .grab_meta import * from .ndvi import * from .scene import * from .surface_reflectance import * from .surface_temp import * from .toa_radiance import * from .toa_reflectance import * from dnppy import core # standard imports import os, sys, time, math, arcpy, shutil if core.check_module("numpy"): import numpy # arcpy imports if arcpy.CheckExtension('Spatial') == 'Available': arcpy.CheckOutExtension('Spatial') from arcpy.sa import * from arcpy import env arcpy.env.overwriteOutput = True
def NAtoCSV_trans(inSpace, inGdb, inNetworkDataset, impedanceAttribute, accumulateAttributeName, inOrigins, inDestinations, outNALayerName, outFile, outField): ''' Same as NAtoCSV, but removed "oneway" since Transit network doesnot have this attribute Also changed the SNAP code to "ions" for all stations ''' fields = outField import arcpy from arcpy import env try: #Check out the Network Analyst extension license if arcpy.CheckExtension("Network") == "Available": arcpy.CheckOutExtension("Network") else: # Raise a custom exception print "Network license unavailable, make sure you have network analyst extension installed." #Check out the Network Analyst extension license arcpy.CheckOutExtension("Network") #Set environment settings env.workspace = inSpace + inGdb env.overwriteOutput = True #Create a new OD Cost matrix layer. outNALayer = arcpy.na.MakeODCostMatrixLayer(inNetworkDataset, outNALayerName, impedanceAttribute, "#", "#", accumulateAttributeName, "ALLOW_UTURNS","#","NO_HIERARCHY","#","NO_LINES","#") #Get the layer object from the result object. The OD cost matrix layer can #now be referenced using the layer object. outNALayer = outNALayer.getOutput(0) #Get the names of all the sublayers within the OD cost matrix layer. subLayerNames = arcpy.na.GetNAClassNames(outNALayer) #Stores the layer names that we will use later originsLayerName = subLayerNames["Origins"] destinationsLayerName = subLayerNames["Destinations"] linesLayerName = subLayerNames["ODLines"] #Adjust field names #Exploit the fact that the detector feature is named hd_ML_snap, (or AllStationsML) #change the field mapping of Name to id_stn oriField = "Name ID_TAZ12A #" oriSort = "ID_TAZ12A" destField = "Name ID_TAZ12A #" destSort = "ID_TAZ12A" searchMetro = "BlueLine_Split SHAPE;GoldLine_split SHAPE;GreenLine_split SHAPE;LABus_prj NONE;LABus_prj_conn NONE;Metro_Tiger_Conn SHAPE;Orange_Conn SHAPE;OrangeLine_split SHAPE;RedLine_split SHAPE;Silver_Conn SHAPE;SilverLine_split SHAPE;TAZ_Tiger_Conn NONE;tl_2012_LAC_prj NONE;BusStopsWLines_prj NONE;Metro_Tiger_Conn_pt SHAPE;Orange_Conn_pt SHAPE;Silver_Conn_pt SHAPE;PreBusDPS_ND_Junctions NONE" searchTAZ = "BlueLine_Split NONE;GoldLine_split NONE;GreenLine_split NONE;LABus_prj NONE;LABus_prj_conn NONE;Metro_Tiger_Conn NONE;Orange_Conn NONE;OrangeLine_split NONE;RedLine_split NONE;Silver_Conn NONE;SilverLine_split NONE;TAZ_Tiger_Conn SHAPE;tl_2012_LAC_prj NONE;BusStopsWLines_prj NONE;Metro_Tiger_Conn_pt NONE;Orange_Conn_pt NONE;Silver_Conn_pt NONE;PreBusDPS_ND_Junctions NONE" print "Origins: ", inOrigins, " Destinations: ", inDestinations if "Station" in inOrigins: oriField = "Name id_stn #" oriSort = "id_stn" arcpy.AddLocations_na(outNALayer, originsLayerName, inOrigins, oriField, sort_field = oriSort, append = "CLEAR", search_criteria = searchMetro) print "loaded stations onto transit network (search_criteria)" else: arcpy.AddLocations_na(outNALayer, originsLayerName, inOrigins, oriField, sort_field = oriSort, append = "CLEAR", search_criteria = searchTAZ) print "loaded stations onto network" if "Station" in inDestinations: destField = "Name id_stn #" destSort = "id_stn" arcpy.AddLocations_na(outNALayer, destinationsLayerName, inDestinations, destField, sort_field = destSort, append = "CLEAR", search_criteria = searchMetro) print "loaded stations onto transit network (search_criteria)" else: arcpy.AddLocations_na(outNALayer, destinationsLayerName, inDestinations, destField, sort_field = destSort, append = "CLEAR", search_criteria = searchTAZ) print "loaded stations onto network" #Solve the OD cost matrix layer print "Begin Solving" arcpy.na.Solve(outNALayer) print "Done Solving" # Extract lines layer, export to CSV for lyr in arcpy.mapping.ListLayers(outNALayer): if lyr.name == linesLayerName: with open(outFile, 'w') as f: #f.write(','.join(fields)+'\n') # csv headers with arcpy.da.SearchCursor(lyr, fields) as cursor: print "Successfully created lines searchCursor. Exporting to " + outFile for row in cursor: f.write(','.join([str(r) for r in row])+'\n') # Deleteing using del outNALayer is not enough. Need to delete within arcpy to release arcpy.Delete_management(outNALayer) except Exception as e: # If an error occurred, print line number and error message import sys tb = sys.exc_info()[2] print "An error occurred in NAtoCSV_Trans line %i" % tb.tb_lineno print str(e) finally: #Check the network analyst extension license back in, regardless of errors. arcpy.CheckInExtension("Network")
def main(): # 0: Setting computing environment arcpy.env.overwriteOutput = True #Such that files can be overwritten arcpy.env.workspace = r"C:\Temp\MTWEB" #Setting the workspace if arcpy.CheckExtension( "Spatial") == "Available": #Check out spatial analyst extension arcpy.CheckOutExtension("Spatial") rs = arcpy.SpatialReference( 28992 ) #Getting reference system for RD_New, GCS_Amersfoort to project geodata # 1: Getting data from Foursquare, store it as json and as shapefile #First municipality jsonfile1 = os.path.join(arcpy.env.workspace, 'Utrechtfoodfsdata.json') municipality1 = getMunicipality( "Utrecht", filen=r"C:\Temp\MTWEB\wijkenbuurten2014\gem_2014.shp", fieldname="GM_NAAM") city1 = 'Utrecht, NL' fsdata1 = getFSdata(city=city1, section='food') processFSPlaces(fsdata1, jsonfile1) result1shp = os.path.join(arcpy.env.workspace, "Utrechtfood.shp") d = loadJson(jsonfile1) json2SHP(d, result1shp, ['cat', 'rating'], rs) #Second municipality jsonfile2 = os.path.join(arcpy.env.workspace, 'Zwollefoodfsdata.json') municipality2 = getMunicipality( "Zwolle", filen=r"C:\Temp\MTWEB\wijkenbuurten2014\gem_2014.shp", fieldname="GM_NAAM") city2 = 'Zwolle, NL' fsdata2 = getFSdata(city=city2, section='food') processFSPlaces(fsdata2, jsonfile2) result2shp = os.path.join(arcpy.env.workspace, "Zwollefood.shp") d = loadJson(jsonfile2) json2SHP(d, result2shp, ['cat', 'rating'], rs) # 2: Generating topics from webtexts, store it as json, and as shapefile jsonfile = os.path.join(arcpy.env.workspace, 'result.json') addJSON( jsonfile1, jsonfile2, jsonfile ) #This adds the two jsonfiles from two municipalities into a single one texts, ids = getTexts( jsonfile, 'webtext') #This loads the texts contained a certain key topics = getTopics( texts, ids, language='dutch', showwordcloud=False ) #This method runs LDA to get topic probabilities for each loaded text outfile = os.path.join(arcpy.env.workspace, 'webtopics.json') joinJSON( jsonfile, topics, outfile, ids ) #This joins the topic probabilities and the json file (for those places having texts) topicshp = os.path.join( arcpy.env.workspace, r"webtopics.shp") #This stores the topics into a single shapefile d = loadJson(outfile) topicnames = topics[0].keys() keys = ['cat', 'rating'] + topicnames json2SHP(d, topicshp, keys, rs) # 3: Geoprocessing points with topics #For 1st municipality, generates neighborhood file. Then generates an accessibility raster (density) for each topic and aggregates it into a neighborhood table arcpy.env.extent = getExtentfromFile(result1shp) buurt1 = getCityNeighborhoods(buurtfile="wijkenbuurten2014/buurt_2014.shp", within=municipality1) for t in normalizeFieldList(topicnames): kdensrast = kdensityRaster(topicshp, 'U', t) densbuurt = aggRasterinNeighborhoods( kdensrast, buurt1) #aggregate means into neighborhoods #For 2nd municipality, generates neighborhood file. Then generates an accessibility raster (density) for each topic and aggregates it into a neighborhood table arcpy.env.extent = getExtentfromFile(result2shp) buurt2 = getCityNeighborhoods(buurtfile="wijkenbuurten2014/buurt_2014.shp", within=municipality2) for t in normalizeFieldList(topicnames): kdensrast = kdensityRaster(topicshp, 'Z', t) densbuurt = aggRasterinNeighborhoods( kdensrast, buurt2) #aggregate means into neighborhoods
try: with open(INPUTFILE) as f: INPUTDATA = imp.load_source('INPUTDATA', '', f) except ImportError: print("Could not find properly formatted input file.") # Check out 3D analyst extension class LicenseError(Exception): """ DOC STRING """ pass try: if arcpy.CheckExtension("3D") == "Available": arcpy.CheckOutExtension("3D") else: # raise a custom exception raise LicenseError except LicenseError: print("3D Analyst license is unavailable") except arcpy.ExecuteError: print(arcpy.GetMessages(2)) # Allow overwrite output arcpy.env.overwriteOutput = True # Generated folders OUTPUTPATH = os.path.join(INPUTDATA.MAPPING_FOLDER, "OUTPUT/") RASTER_FOLDER = os.path.join(OUTPUTPATH, "raster/")
def RunTest(): try: arcpy.AddMessage("Starting Test: RangeFans") if arcpy.CheckExtension("Spatial") == "Available": arcpy.CheckOutExtension("Spatial") else: # Raise a custom exception raise Exception("LicenseError") # WORKAROUND print "Creating New Scratch Workspace (Workaround)" TestUtilities.createScratch() # Verify the expected configuration exists inputPointsFC = os.path.join(TestUtilities.inputGDB, "sampleRangePoints") inputSurface = os.path.join(TestUtilities.inputGDB, "Jbad_SRTM_USGS_EROS") outputRangeFansFC = os.path.join(TestUtilities.outputGDB, "RangeFans") outputRangeVizFC = os.path.join(TestUtilities.outputGDB, "RangeViz") toolbox = TestUtilities.toolbox sr = arcpy.SpatialReference( 32642) #WGS_1984_UTM_Zone_42N using factoryCode # Check For Valid Input objects2Check = [] objects2Check.extend([inputPointsFC, inputSurface, toolbox]) for object2Check in objects2Check: desc = arcpy.Describe(object2Check) if desc == None: raise Exception("Bad Input") else: print("Valid Object: " + desc.Name) # Set environment settings print("Running from: " + str(TestUtilities.currentPath)) print("Geodatabase path: " + str(TestUtilities.geodatabasePath)) arcpy.env.overwriteOutput = True arcpy.env.scratchWorkspace = TestUtilities.scratchGDB arcpy.ImportToolbox(toolbox, "VandR") inputFeatureCount = int( arcpy.GetCount_management(inputPointsFC).getOutput(0)) print("Input FeatureClass: " + str(inputPointsFC)) print("Input Feature Count: " + str(inputFeatureCount)) if (inputFeatureCount < 1): print("Invalid Input Feature Count: " + str(inputFeatureCount)) maximumRange = 1000.0 bearing = 150.0 traversal = 22.0 ########################################################3 # Execute the Model under test: arcpy.RangeFan_VandR(inputPointsFC, maximumRange, bearing, traversal, inputSurface, outputRangeFansFC, outputRangeVizFC, sr) ########################################################3 # Verify the results outputFeatureCountFans = int( arcpy.GetCount_management(outputRangeFansFC).getOutput(0)) print("Output FeatureClass: " + str(outputRangeFansFC)) print("Output Feature Count: " + str(outputFeatureCountFans)) outputFeatureCountViz = int( arcpy.GetCount_management(outputRangeVizFC).getOutput(0)) print("Output FeatureClass: " + str(outputRangeVizFC)) print("Output Feature Count: " + str(outputFeatureCountViz)) if (outputFeatureCountFans < 1) or (outputFeatureCountViz < 1): print("Invalid Output Feature Count: " + str(outputFeatureCountFans) + ":" + str(outputFeatureCountViz)) raise Exception("Test Failed") # WORKAROUND: delete scratch db print("Deleting Scratch Workspace (Workaround)") TestUtilities.deleteScratch() print("Test Successful") except arcpy.ExecuteError: # Get the tool error messages msgs = arcpy.GetMessages() arcpy.AddError(msgs) # return a system error code sys.exit(-1) except Exception as e: # Get the traceback object tb = sys.exc_info()[2] tbinfo = traceback.format_tb(tb)[0] # Concatenate information together concerning the error into a message string pymsg = "PYTHON ERRORS:\nTraceback info:\n" + tbinfo + "\nError Info:\n" + str( sys.exc_info()[1]) msgs = "ArcPy ERRORS:\n" + arcpy.GetMessages() + "\n" # Return python error messages for use in script tool or Python Window arcpy.AddError(pymsg) arcpy.AddError(msgs) # return a system error code sys.exit(-1) finally: # Check in the 3D Analyst extension arcpy.CheckInExtension("Spatial")