53
ArcGIS Geoprocessing ArcGIS Geoprocessing Advanced Scripting With Python Advanced Scripting With Python Corey Tucker Corey Tucker Nathan Warmerdam Nathan Warmerdam

ArcGIS Geoprocessing Advanced Scripting With Python Corey Tucker Nathan Warmerdam

Embed Size (px)

Citation preview

ArcGIS GeoprocessingArcGIS GeoprocessingAdvanced Scripting With PythonAdvanced Scripting With Python

Corey TuckerCorey TuckerNathan WarmerdamNathan Warmerdam

Workshop OutlineWorkshop Outline

• Review of scripting languagesReview of scripting languages– What is supported? What is recommended? Why?What is supported? What is recommended? Why?

• Data Access with cursorsData Access with cursors– Review types and optionsReview types and options– Working with feature geometryWorking with feature geometry

• Creating and using objects for parameter valuesCreating and using objects for parameter values• How to create a script toolHow to create a script tool• Making scripts more efficientMaking scripts more efficient

– Use of layers and table viewsUse of layers and table views– Calling modelsCalling models

• Effective Error HandlingEffective Error Handling• SummarySummary

Scripting LanguagesScripting Languages

• Many to choose from for geoprocessing tasksMany to choose from for geoprocessing tasks– PythonPython– VBScriptVBScript– JScriptJScript– PerlPerl– OthersOthers

• Any language that supports COM IDispatch may Any language that supports COM IDispatch may be usedbe used

• Python is the most commonly used by our users Python is the most commonly used by our users and is what is most commonly documentedand is what is most commonly documented

Scripting LanguagesScripting LanguagesPythonPython

• Why is Python recommended by ESRIWhy is Python recommended by ESRI– It is free!It is free!– Established user communityEstablished user community– Simple when it needs to beSimple when it needs to be– Easy to maintainEasy to maintain– ScalableScalable– Cross platform (windows, UNIX, Linux)Cross platform (windows, UNIX, Linux)– Many IDE’s to choose fromMany IDE’s to choose from– Supports object-oriented and modular designsSupports object-oriented and modular designs

Scripting LanguagesScripting LanguagesPythonPython

• What version is supported?What version is supported?– ArcGIS installs version 2.1, but all versions from 2.1 ArcGIS installs version 2.1, but all versions from 2.1

up to 2.4.1 are supportedup to 2.4.1 are supported

• Why 2.1?Why 2.1?– Due to installation problems of PythonWin for later Due to installation problems of PythonWin for later

versions of Python, ESRI had to ship version 2.1.versions of Python, ESRI had to ship version 2.1.

• How can I upgrade my version of PythonHow can I upgrade my version of Python– Download install for 2.4.1 Download install for 2.4.1 – Download PythonWin for 2.4.1Download PythonWin for 2.4.1– Read Knowledge Base document #26872 from Read Knowledge Base document #26872 from

support.esri.comsupport.esri.com

ArcGIS 9.2ArcGIS 9.2BulletinBulletin

• A native Python module for ArcGIS will be A native Python module for ArcGIS will be includedincluded– Based on version 2.4.1Based on version 2.4.1– Eliminates need for PythonWinEliminates need for PythonWin– Allows better error messagingAllows better error messaging– Cross platform supportCross platform support

• Can be used to run scripts on Unix and Linux that have a 9.2 Can be used to run scripts on Unix and Linux that have a 9.2 ArcGIS Engine installationArcGIS Engine installation

– 9.0 and 9.1 scripts will just work. Older Dispatch 9.0 and 9.1 scripts will just work. Older Dispatch methodology will still be supported.methodology will still be supported.

Scripting Documentation Scripting Documentation and Samplesand Samples

• Writing Geoprocessing Scripts with ArcGISWriting Geoprocessing Scripts with ArcGIS– PDF in Documentation LibraryPDF in Documentation Library– Explanation of methods and samplesExplanation of methods and samples

• ArcGIS Online HelpArcGIS Online Help– Same content as PDFSame content as PDF– Specific help and samples for all of the Specific help and samples for all of the

geoprocessor’s methods and propertiesgeoprocessor’s methods and properties• Geoprocessing Programming GuideGeoprocessing Programming Guide

– Logical layout of scripting objects with their methods Logical layout of scripting objects with their methods and propertiesand properties

– Quick ReferenceQuick Reference

Section 1: CursorsSection 1: Cursors

• Geoprocessing workflows commonly require record by record Geoprocessing workflows commonly require record by record access of field valuesaccess of field values– Including the geometry fieldIncluding the geometry field

• This is done using an object that points to a record in a table This is done using an object that points to a record in a table or feature class called a cursoror feature class called a cursor

• ExamplesExamples– Using a field value in an logical expressionUsing a field value in an logical expression

ifif row.soiltype == “loam”: row.soiltype == “loam”: row.group = 2row.group = 2

– Moving values from one table or feature class to anotherMoving values from one table or feature class to another

ifif row1.parcelid == row2.parcelid: row1.parcelid == row2.parcelid: row1.owner = row2.ownerrow1.owner = row2.owner

– Accessing properties of a feature’s geometryAccessing properties of a feature’s geometry

printprint row.shape.FirstPoint row.shape.FirstPoint

Accessing DataAccessing Datawith Cursorswith Cursors

Accessing DataAccessing Datawith Cursorswith Cursors

• There are three types of cursorsThere are three types of cursors– Search CursorSearch Cursor

• Read-only accessRead-only access

– Update CursorUpdate Cursor• Read/Write/Delete access but no new recordsRead/Write/Delete access but no new records

– Insert CursorInsert Cursor• Read/Write access with capability of creating new recordsRead/Write access with capability of creating new records

Accessing DataAccessing Datawith a Search Cursorwith a Search Cursor

• A row object is returned from the search cursor A row object is returned from the search cursor objectobject

• Fields are accessed as properties of the row Fields are accessed as properties of the row objectobject

• Use the row object’s GetValue and SetValue Use the row object’s GetValue and SetValue methods if your field name is a variablemethods if your field name is a variable

• Destroy the row and cursor objects to remove Destroy the row and cursor objects to remove read locks on the data sourceread locks on the data source

Accessing DataAccessing Datawith a Search Cursorwith a Search Cursor

fromfrom win32com.client win32com.client importimport Dispatch Dispatchgp = Dispatch("esriGeoprocessing.gpDispatch.1")gp = Dispatch("esriGeoprocessing.gpDispatch.1")rows = gp.SearchCursor("D:/St_Johns/data.mdb/roads")rows = gp.SearchCursor("D:/St_Johns/data.mdb/roads")row = rows.Next()row = rows.Next()# Print concatenated values of road name and road type# Print concatenated values of road name and road typewhilewhile row: row: printprint row.name + row.GetValue("type") row.name + row.GetValue("type") row = rows.Next()row = rows.Next()# Delete the row and cursor objects so no locks remain# Delete the row and cursor objects so no locks remaindeldel row rowdeldel rows rows

Accessing DataAccessing Datawith Cursorswith Cursors

• A where clause may be used to limit the records A where clause may be used to limit the records returned by the cursorreturned by the cursor– Same as defining a definition query on a layerSame as defining a definition query on a layer

fromfrom win32com.client win32com.client importimport Dispatch Dispatchgp = Dispatch("esriGeoprocessing.gpDispatch.1")gp = Dispatch("esriGeoprocessing.gpDispatch.1")rows = gp.SearchCursor("D:/St_Johns/data.mdb/roads", rows = gp.SearchCursor("D:/St_Johns/data.mdb/roads", “ “[neighborhood] = "Shea_Heights")[neighborhood] = "Shea_Heights")row = rows.Next()row = rows.Next()# Print concatenated values of road name and road type# Print concatenated values of road name and road typewhilewhile row: row: printprint row.name + row.GetValue("type") row.name + row.GetValue("type") row = rows.Next()row = rows.Next()deldel row rowdeldel rows rows

Reading Feature Reading Feature GeometryGeometry

• You must understand the hierarchy for geometry in order You must understand the hierarchy for geometry in order to use itto use it– A feature class is made of featuresA feature class is made of features– A feature is made of partsA feature is made of parts– A part is made of pointsA part is made of points

• In Python termsIn Python terms– A single part feature looks like thisA single part feature looks like this

[pnt, pnt, pnt][pnt, pnt, pnt]– A multipart polygon feature looks like thisA multipart polygon feature looks like this

[[pnt, pnt, pnt],[pnt, pnt, pnt]][[pnt, pnt, pnt],[pnt, pnt, pnt]]– A single part polygon feature with a hole (inner ring) looks likeA single part polygon feature with a hole (inner ring) looks like

[[[pnt, pnt, pnt, ,pnt, pnt, pnt]][pnt, pnt, pnt, ,pnt, pnt, pnt]]

Reading Feature Reading Feature GeometryGeometry

• A null point is used as a separator between rings (holes) A null point is used as a separator between rings (holes) in a polygon partin a polygon part

• Use the PartCount property to get the number of parts Use the PartCount property to get the number of parts for a featurefor a feature

• Use the GetPart method to retrieve the desired partUse the GetPart method to retrieve the desired part # Reading lines# Reading linesx = 0x = 0whilewhile x < feat.PartCount: x < feat.PartCount: roadArray = feat.GetPart(x)roadArray = feat.GetPart(x) pnt = roadArray.Next()pnt = roadArray.Next() whilewhile pnt: pnt: printprint pnt.x + "," + pnt.y pnt.x + "," + pnt.y pnt = RoadArray.Next()pnt = RoadArray.Next() x = x + 1x = x + 1

Reading Feature Reading Feature GeometryGeometry

• Features may be projected on-the-fly to another Features may be projected on-the-fly to another coordinate system using the Spatial Reference coordinate system using the Spatial Reference parameterparameter

• Create the Spatial Reference by describing another Create the Spatial Reference by describing another dataset dataset

# Describe features class with a GCS# Describe features class with a GCSdesc = gp.Describe("D:/data.mdb/geo_roads")desc = gp.Describe("D:/data.mdb/geo_roads")# Create search cursor, using GCS spatial reference# Create search cursor, using GCS spatial referencerows = GP.SearchCursor("D:/data.mdb/roads","",rows = GP.SearchCursor("D:/data.mdb/roads","", desc.SpatialReference)desc.SpatialReference)row = rows.Next()row = rows.Next()

Demo 1 – Reading Feature GeometryDemo 1 – Reading Feature Geometry

Reading Feature Reading Feature Geometry - TipsGeometry - Tips

• Use field values instead of the properties of the Use field values instead of the properties of the geometry object if speed is really importantgeometry object if speed is really important– LengthLength– AreaArea

• If you want the extent or centroid of a complex If you want the extent or centroid of a complex feature try creating simple features in a new feature try creating simple features in a new feature classfeature class– Features to Point Features to Point – Feature Envelope to Polygon Feature Envelope to Polygon

• Using fields or simple geometry is faster that Using fields or simple geometry is faster that querying the geometry object of a complex querying the geometry object of a complex featurefeature

Writing FeatureWriting FeatureGeometryGeometry

• Insert cursors must be used to create new Insert cursors must be used to create new featuresfeatures

rows = GP.InsertCursor("D:/data.mdb/roads“)rows = GP.InsertCursor("D:/data.mdb/roads“)row = rows.NewRow()row = rows.NewRow()

• Use the Point and Array objects to create Use the Point and Array objects to create feature partsfeature parts

• A part may be used to set a geometry fieldA part may be used to set a geometry field– A multipart feature is an array containing other A multipart feature is an array containing other

arrays, where each array is a partarrays, where each array is a part

Writing FeatureWriting FeatureGeometryGeometry

# Open an insert cursor for the feature class# Open an insert cursor for the feature classcur = GP.InsertCursor(fcname)cur = GP.InsertCursor(fcname)# Create the array and point objects needed to create a # Create the array and point objects needed to create a

featurefeaturelineArray = GP.CreateObject("Array")lineArray = GP.CreateObject("Array")pnt = GP.CreateObject("Point")pnt = GP.CreateObject("Point")# Add two points to the array# Add two points to the arraypnt.x = 358331pnt.x = 358331pnt.y = 5273193pnt.y = 5273193lineArray.Add(pnt)lineArray.Add(pnt)pnt.x = 358337pnt.x = 358337pnt.y = 5272830pnt.y = 5272830lineArray.Add(pnt)lineArray.Add(pnt)# Create a new row, or feature, in the feature class# Create a new row, or feature, in the feature classfeat = cur.NewRow()feat = cur.NewRow()# Set the geometry of the new feature to the array of points# Set the geometry of the new feature to the array of pointsfeat.shape = lineArrayfeat.shape = lineArray# Insert the feature# Insert the featurecur.InsertRow(feat)cur.InsertRow(feat)

Writing FeatureWriting FeatureGeometryGeometry

• The geoprocessor checks the validity of the The geoprocessor checks the validity of the geometry before it is insertedgeometry before it is inserted– Problems such as invalid ring order or ring orientation Problems such as invalid ring order or ring orientation

are corrected automaticallyare corrected automatically– Uses the same process found in the Check and Uses the same process found in the Check and

Repair Geometry toolsRepair Geometry tools

• Writing features requires an exclusive schema Writing features requires an exclusive schema lock on the feature classlock on the feature class– Use the TestSchemaLock method to see if the data is Use the TestSchemaLock method to see if the data is

being used by another processbeing used by another process

ArcGIS 9.2ArcGIS 9.2BulletinBulletin

• Cursor performance will be FASTER!Cursor performance will be FASTER!– Much faster for Update operationsMuch faster for Update operations

• New option to limit the returned fields on a rowNew option to limit the returned fields on a row• New option to sort the rows on a field or set of New option to sort the rows on a field or set of

fieldsfields• 9.0 and 9.1 scripts will just work9.0 and 9.1 scripts will just work• Speed enhancements will be included in Service Speed enhancements will be included in Service

Pack 1 for ArcGIS 9.1Pack 1 for ArcGIS 9.1

Section 2: Complex ParametersSection 2: Complex Parameters

Tools and ParametersTools and Parameters

• Each geoprocessing tool has a collection of Each geoprocessing tool has a collection of parameter valuesparameter values

• Parameters define how the tool will workParameters define how the tool will work

Using Objects forUsing Objects forParametersParameters

• Most tool parameters are easy to define using a Most tool parameters are easy to define using a string or a number, such as a data path or buffer string or a number, such as a data path or buffer distancedistance

• Some parameters are more complex and have Some parameters are more complex and have complicated text string representations, complicated text string representations, – spatial reference or field mappingspatial reference or field mapping

• Instead of using text strings, use objectsInstead of using text strings, use objects

Using Objects forUsing Objects forParametersParameters

• Objects either created directly by Objects either created directly by – The geoprocessor’s CreateObject methodThe geoprocessor’s CreateObject method– Another object, such as the descriptive object created Another object, such as the descriptive object created

by the Describe methodby the Describe method– A tool, such as Create Spatial ReferenceA tool, such as Create Spatial Reference

Using Objects forUsing Objects forParametersParameters

• Creating a geodatabase feature datasetCreating a geodatabase feature dataset

SR = Spatial ReferenceSR = Spatial Reference

fromfrom win32com.client win32com.client importimport Dispatch Dispatchgp = Dispatch("esriGeoprocessing.GPDispatch.1")gp = Dispatch("esriGeoprocessing.GPDispatch.1")# Describe a dataset that has the desired SR# Describe a dataset that has the desired SRdesc = gp.Describe("D:/St_johns/city.mdb/city_boundary")desc = gp.Describe("D:/St_johns/city.mdb/city_boundary")# Create the FDS using the describe object's SR Object# Create the FDS using the describe object's SR Object gp.CreateFeatureDataset("D:/St_johns/city.mdb“,"NewFDS",gp.CreateFeatureDataset("D:/St_johns/city.mdb“,"NewFDS", desc.SpatialReference)desc.SpatialReference)

Using Objects forUsing Objects forParametersParameters

• Value TablesValue Tables– Used to define any tool parameter that accepts more Used to define any tool parameter that accepts more

than one value (e.g. Merge)than one value (e.g. Merge)– Multivalue parameters may be expressed as Multivalue parameters may be expressed as

• A string A string ((""value1;value2;value3value1;value2;value3""))• As a Value TableAs a Value Table

– Use LoadFromString method to load a multivalue Use LoadFromString method to load a multivalue strting that may be passed as a script argumentstrting that may be passed as a script argument

– Use ExportFromString to create an output argument Use ExportFromString to create an output argument valuevalue

• Useful for script toolsUseful for script tools

Using Objects forUsing Objects forParametersParameters

• Overlay tools, such as Union and Intersect use Overlay tools, such as Union and Intersect use Value Tables with multiple columnsValue Tables with multiple columns– Difficult to parse multivalue string when more than Difficult to parse multivalue string when more than

one column is usedone column is used

• Value Tables with multiple columns are easy to Value Tables with multiple columns are easy to navigatenavigate

("D:/data/new roads" 1;D:/data/soils 2)("D:/data/new roads" 1;D:/data/soils 2)

Section 3: Script ToolsSection 3: Script Tools

Creating Tools Creating Tools from Scriptsfrom Scripts

• Why?Why?– The script is generic and can be used with other dataThe script is generic and can be used with other data

• Script can use arguments from the userScript can use arguments from the user

– You want to use a script in ModelBuilderYou want to use a script in ModelBuilder• Incorporate another system with a script wrapper or do Incorporate another system with a script wrapper or do

branchingbranching

– You want to easily share your scriptYou want to easily share your script• Not everyone knows how to run a stand-alone scriptNot everyone knows how to run a stand-alone script• Puts a familiar face on your workPuts a familiar face on your work

Creating Tools Creating Tools from Scriptsfrom Scripts

• Step 1: Create argument variablesStep 1: Create argument variables– Can use sys.argv[ ], but this is subject to windows Can use sys.argv[ ], but this is subject to windows

limitations (1024 characters)limitations (1024 characters)– Should use GetParameterAsText, especially with Should use GetParameterAsText, especially with

multivalue parametersmultivalue parameters

Creating Tools Creating Tools from Scriptsfrom Scripts

• Step 2: MessagingStep 2: Messaging– Return informative messages during execution of the Return informative messages during execution of the

scriptscript– Return error messages when a problem arisesReturn error messages when a problem arises

Creating Tools Creating Tools from Scriptsfrom Scripts

• Step 3: Add the script to a toolboxStep 3: Add the script to a toolbox– Give the tool a name, label and descriptionGive the tool a name, label and description– Set the tool source and use relative paths option if Set the tool source and use relative paths option if

you plan on sharing the toolyou plan on sharing the tool– Define the parameters that will correspond to your Define the parameters that will correspond to your

scriptscript

Creating Tools Creating Tools from Scriptsfrom Scripts

• Step 3: Defining ParametersStep 3: Defining Parameters– Parameters have several propertiesParameters have several properties

• Name: What you see on the dialog and on the command Name: What you see on the dialog and on the command line.line.

• Type: Is it required, optional or derived?Type: Is it required, optional or derived?• Direction: Is the data being used (input) or created (output)?Direction: Is the data being used (input) or created (output)?• Multivalue: Do you want a list of values or just one?Multivalue: Do you want a list of values or just one?• Default: Is there a default value?Default: Is there a default value?• Environment: Does an environment provide a default value?Environment: Does an environment provide a default value?• Domain: Do you want to provide a choice or limit input Domain: Do you want to provide a choice or limit input

values?values?• Dependency: Does this parameter depend on another?Dependency: Does this parameter depend on another?

Creating Tools Creating Tools from Scriptsfrom Scripts

• Step 3: Derived ParametersStep 3: Derived Parameters– All tools that will be used in ModelBuilder should have All tools that will be used in ModelBuilder should have

an outputan output– If the script updates an input dataset, create a derived If the script updates an input dataset, create a derived

parameter and set its dependency to the input parameter and set its dependency to the input parameterparameter

ValueValue

Creating Tools Creating Tools from Scriptsfrom Scripts

• Step 3: Parameter DependencyStep 3: Parameter Dependency– Some parameter types have built-in behavior when Some parameter types have built-in behavior when

there is a parameter dependencythere is a parameter dependency• Fields with an Input table or feature classFields with an Input table or feature class

– Fields will be populated automatically in the dialogFields will be populated automatically in the dialog

• Derived parameter with an input parameterDerived parameter with an input parameter– The derived parameter value will automatically be set to the The derived parameter value will automatically be set to the

value of the input parameter it depends uponvalue of the input parameter it depends upon

Demo 2: Creating A Script ToolDemo 2: Creating A Script Tool

Creating Tools Creating Tools from Scriptsfrom Scripts

• AML is a supported source for script toolsAML is a supported source for script tools– Need to change the default behavior of an AML to Need to change the default behavior of an AML to

support thissupport this• By default it must execute with arguments when openedBy default it must execute with arguments when opened

• Use the RegisterAMLAsExecutable registry file Use the RegisterAMLAsExecutable registry file to make this changeto make this change– File is in the ArcGIS\ArcToolbox\Scripts folderFile is in the ArcGIS\ArcToolbox\Scripts folder

• Any ArcInfo workstation module is supportedAny ArcInfo workstation module is supported– AML must start in the Arc module and then call other AML must start in the Arc module and then call other

modulesmodules– Display windows and form menus are supportedDisplay windows and form menus are supported

Section 3: Tips for EfficiencySection 3: Tips for Efficiency

Efficiency TipsEfficiency Tips

• When working with selections, use layers and When working with selections, use layers and views instead of using the Select toolviews instead of using the Select tool– Layers and views are in memory and avoid costs of Layers and views are in memory and avoid costs of

writing to diskwriting to disk

• Use Make Feature Layer, Make Raster Layer or Use Make Feature Layer, Make Raster Layer or Make Table ViewMake Table View

• Use Select By Attribute to update the selection Use Select By Attribute to update the selection or provide a where clause when creating the or provide a where clause when creating the layer or viewlayer or view

Efficiency TipsEfficiency Tips

• Call models from your scriptsCall models from your scripts– Instead of rewriting a model as a script, reference the Instead of rewriting a model as a script, reference the

model’s toolbox and call it as a toolmodel’s toolbox and call it as a tool– Simplifies codeSimplifies code

fromfrom win32com.client win32com.client importimport Dispatch Dispatchgp = Dispatch("esriGeoprocessing.gpDispatch.1")gp = Dispatch("esriGeoprocessing.gpDispatch.1")# Add custom toolbox# Add custom toolboxgp.AddToolbox("D:/Data/St_Johns/MyTools.tbx")gp.AddToolbox("D:/Data/St_Johns/MyTools.tbx")gp.MyRoadsModel("D:/Data/St_Johns/urban_roads",100,gp.MyRoadsModel("D:/Data/St_Johns/urban_roads",100, "C:/temp/results")"C:/temp/results")

Efficiency TipsEfficiency Tips

• Use Python Lists and Dictionaries for frequent Use Python Lists and Dictionaries for frequent access of attributesaccess of attributes– Instead of reading through a table multiple times with Instead of reading through a table multiple times with

a cursor, read it once and load the values into a cursor, read it once and load the values into memorymemory

– Use a list for an ordered collection of valuesUse a list for an ordered collection of values– Use a dictionary if you have an unordered collection Use a dictionary if you have an unordered collection

of values and want to access values using a keyof values and want to access values using a key

• Great for working with coordinatesGreat for working with coordinates– Many examples in the source scripts of the Spatial Many examples in the source scripts of the Spatial

Statistics toolsStatistics tools

Section 4: Error HandlingSection 4: Error Handling

Error HandlingError Handling

• The Geoprocessor is just another COM Dispatch The Geoprocessor is just another COM Dispatch object to Python, or any other languageobject to Python, or any other language– Error messages are less than helpfulError messages are less than helpful

• Tool messages must be retrieved from the Tool messages must be retrieved from the geoprocessorgeoprocessor

• Scripts must add error handling routines to catch Scripts must add error handling routines to catch errors and return tool messageserrors and return tool messages

Error HandlingError Handling

• Non-tool methods on the Geoprocessor do not Non-tool methods on the Geoprocessor do not return error messagesreturn error messages– Cursors, Creating Lists, Describe, etcCursors, Creating Lists, Describe, etc

• Use the Raise statement to trigger specific Use the Raise statement to trigger specific exceptionsexceptions– Especially useful when using tools and native Especially useful when using tools and native

methods togethermethods together– Provides more meaningful context for messagesProvides more meaningful context for messages

Error HandlingError Handlingtry:try: # Get the input feature class and make sure it contains polygons# Get the input feature class and make sure it contains polygons input = sys.argv[1]input = sys.argv[1] dsc = gp.Describe(input)dsc = gp.Describe(input) ifif dsc.ShapeType != "polygon": raise "ShapeError" dsc.ShapeType != "polygon": raise "ShapeError" # Get the new field name# Get the new field name fieldname = sys.argv[2]fieldname = sys.argv[2] # Make sure shape_length and shape_area fields exist# Make sure shape_length and shape_area fields exist ifif gp.ListFields(input,"Shape_area").Next() and \ gp.ListFields(input,"Shape_area").Next() and \ gp.ListFields(input,"Shape_length").Next():gp.ListFields(input,"Shape_length").Next(): # Add the new field and calculate the value# Add the new field and calculate the value gp.AddField(input, fieldname, "double")gp.AddField(input, fieldname, "double") gp.CalculateField(input,fieldname,gp.CalculateField(input,fieldname, "[Shape_area] / [Shape_length]")"[Shape_area] / [Shape_length]") elseelse:: raise "FieldError"raise "FieldError"exceptexcept "ShapeError": "ShapeError": printprint "Input does not contain polygons" "Input does not contain polygons"exceptexcept "FieldError": "FieldError": printprint "Input does not shape area and length fields" "Input does not shape area and length fields"exceptexcept:: printprint gp.GetMessages(2) gp.GetMessages(2)

Error HandlingError Handling

• Use the sys module to access python syntax Use the sys module to access python syntax errorserrors– Useful when using Useful when using execexec or or evaleval functions functions– Must import the sys moduleMust import the sys module

exceptexcept:: msgs = gp.GetMessages()msgs = gp.GetMessages() ifif msgs: msgs: AddMsgAndPrint(msgs,2)AddMsgAndPrint(msgs,2) value = sys.exc_info()[1]value = sys.exc_info()[1] AddMsgAndPrint(value.msg + ": " + value.text ,2)AddMsgAndPrint(value.msg + ": " + value.text ,2)

Demo 3: Error HandlingDemo 3: Error Handling

• For additional information about geoprocessing including service For additional information about geoprocessing including service pack information, knowledge base articles, and recent information pack information, knowledge base articles, and recent information about issues go to: about issues go to:

http://http://support.esri.comsupport.esri.com/geoprocessing/geoprocessing

Additional supportAdditional support

• ArcGIS Geoprocessing: Introduction to ModelBuilder Wed 3:30 PM Room:

6E • ArcGIS Geoprocessing: Advanced ModelBuilder

Thu 8:30 AM Room: 6E

• ArcGIS Geoprocessing: An Introduction Wed 1:30 PM Room:

6E

• ArcGIS Geoprocessing: Developing Geoprocessing tools with ArcObjects

Thu 10:30 AM Room: 6E

• ArcGIS Geoprocessing: Using Spatial Statistics in ArcGIS

Thu 1:30 PM Room: 8 • ArcGIS Extension: 3D Analyst Geoprocessing Tools

Thu 3:30 PM Room: 5-B

Additional technical sessionsAdditional technical sessions

• Working with Layers and Table Views in GeoprocessingWed 4:00 -4:30pm

• How to convert pGDB feature classes to .shp in a modelThu 11:30 –

12noon

Island demo’s & Demo Theatre Island demo’s & Demo Theatre sessionssessions

• How to use the Geoprocessing Environment Settings T1 - Tue 10:30 –

11:15amT1 - Wed 1:30 –

2:15pm

• Using Spatial Statistics for Crime Analysis T1 - Thu 9 -10am

• Geoprocessing Tool Documentation and Metadata T1 - Thu 11:15 -

12noon

Island Demo’sIsland Demo’s

Demo theatre sessionsDemo theatre sessions

Thank you!Thank you!

Please fill out your survey formPlease fill out your survey form

Questions?Questions?