Extending Arc GISWith Python
Extending Arc GISWith Python
• Improve productivity
Python 101
• Where do I write Python code?
- IDE like PythonWin; Python window in ArcGIS
• Which lines will run?
var = “a”
if var == “a”:
# Execute indented lines
print “variable is a”
else:
print “variable is not a”
Python 101
• Techniques for iterating or looping
- While loops, counted loops, list loops
- Colon at end of statement
- Indentation determines what is executed
x = 1
while x < 5:
print x
x = x + 1
x = [1, 2, 3, 4]
for num in x:
print num
Python 101
• Case sensitivity
- Variables, functions, etc. are case sensitive
- name „X‟ is not defined, function „X‟ does not exist
# Import ArcPy
import arcpy
• Tool documentation
• arcpy.Usage(“Buffer_analysis”)
Setting environments in Python
• Common environments:
- Workspace, coordinate system, extent
arcpy.env.workspace = “C:/Data”
arcpy.env.extent = “0 0 100 100”
Scripting Geoprocessing Tools
Exercise 1
10 min
Tips & Tricks
• Supports automation of
manual tasks
Batch processing
• Describe function
- Returns an object with properties
print desc.shapeType
>>> “Polyline”
Reading Data Values and Geometry
Cursor Explanation
• SearchCursor
scur = arcpy.SearchCursor(“C:/Data/Roads.shp”)
for row in scur:
print row.getValue(“Name”)
• UpdateCursor
ucur = arcpy.UpdateCursor(“C:/Data/Sites.shp”)
for row in ucur:
log = math.log(row.getValue(“Num”))
row.setValue(“Log”, log)
ucur.updateRow(row)
Reading Geometry
• Feature classes have a geometry field
- Typically (but not always) named Shape
• Returns a geometry object
- Has properties that describe the feature
- area, length, isMultipart, partCount, pointCount, type, ...
• Geometry objects can often be used in place of
feature classes
icur = arcpy.InsertCursor(“C:/Data/Cities.shp”)
row = icur.newRow()
row.setValue(“City”, “Denver”)
row.setValue(“Shape”, arcpy.Point(-104.98, 39.74))
icur.insertRow(row)
ArcPy Cursors
Exercise 3
10 min
Tips & Tricks
• Clean up cursors using a try, except, finally
statement
• Cursors can keep a lock on data
scur = arcpy.SearchCursor(“C:/Data/Roads.shp”)
try:
for row in scur:
print row.getValue(“Name”)
except:
raise
finally:
if scur:
del scur
Spatial Analyst Module
Spatial Analyst Module
• from arcpy.sa import *
• Includes all Spatial Analyst tools
• Integrates Map Algebra into Python
- Defines geographic analysis as algebraic expressions
- Supports mathematical, relational, other operators
- Output on the left-side
• Helper classes that can be used to support complex
parameter
md = arcpy.mapping.MapDocument(”C:/Maps/NtlParks.mxd”)
• Instructor-Led Course
- Introduction to Geoprocessing Scripts Using Python
• Web Course
- Using Python in ArcGIS Desktop 10