1 Getting Started With Python
1 Getting Started With Python
Agenda
8:30 9:30: Python 101 and ArcPy 101
Essentials of the language U Using g ArcPy y to execute g geoprocessing p g tools Python window
10:00 10:15: Map 10:00 p automation 10:15 10:45: Break 10:45 10:45 11:00: Raster analysis and Map Algebra 11:00 11:00 11:45: Tool Design and Validation
Python y 101
Why Python?
ESRI has embraced Python for ArcGIS 10 Python is the language that fulfills the needs of our user community
Easy to learn Excellent for beginners and experts Suitable S it bl for f large l projects j t or small ll scripts i t Cross Cross-platform
Python 101
Clear, easy to read syntax Easy to use, makes it simple to get started Variety of basic data types
Including lists and dictionaries
Comes with a large standard library Supports raising and catching exceptions Code can be grouped into modules and packages Supports S t objectobject bj t-oriented i t d programming i
http://www.python.org/about/
Python at 10.0 10 0
ESRI has fully embraced Python as its language for automation 1. ArcPy site site-package
Includes mapping and Map Algebra support Successor to the arcgisscripting module Python access and interaction from within ArcGIS
arcgisscripting module Cross-platform Cross platform Python 2.4 arcgisscripting module, 9.3 version Pythonic Python 2.5
ArcPy y site-package p g Mapping & Map Algebra support Python window Python 2.6 26
ArcPy y 101
ArcPy improvements
Improved coding experience, such as:
Cursors Classes C Multi Multi-value parameters can be expressed as Python lists Ability to convert rasters to and from NumPy arrays
Resource Center
http://resourcesbeta.esri.com/ content/geoprocessing
Running tools
Tools are accessed as functions on arcpy Environments as properties from arcpy.env class
# ~~~ PYTHON CODE ~~~ import arcpy # Set the workspace arcpy.env.workspace = "c:/st_Johns/GISData.gdb" # Execute Geoprocessing tool arcpy.Intersect_analysis(["roads","urban_area","urban_roads", 5, , "j join")
Environments
Script writers set the environment and tools use it
General settings
Current Workspace, p Output p Spatial p Reference, Extent
Tool messages
Executing E ti a tool t l will ill produce d 3 types t of f messages.
Informative messages (severity = 0) Warning messages (severity = 1) Error messages (severity = 2)
# start try block try: arcpy.Buffer("c:/ws/roads.shp", "c:/outws/roads10.shp", 10) # If an error occurs when running a geoprocessing tool, tool # print the tool messages except arcpy.ExecuteError: print arcpy.GetMessages(2) # Any other error except Exception as e: print e.message
Functions
Functions perform useful scripting tasks
Access geoprocessing tool messages (GetMessages (GetMessages) ) List data to for batch p processing g (ListFeatureClasses (ListFeatureClasses, C , ListFields, ListFields , nine other List functions) Retrieve a datasets properties (Describe (Describe) )
import arcpy # Set the workspace for ListFeatureClasses function arcpy env workspace = "c:/test" arcpy.env.workspace c:/test # For each fc, create a scratch name and clip for fc in arcpy.ListFeatureClasses(): outName = arcpy.CreateScratchName("clipped_" + fc, "", "featureclass", arcpy.env.workspace) arcpy Clip analysis(fc "boundary" arcpy.Clip_analysis(fc, boundary , outName)
Describe
Returns an object with dynamic properties Allows script to determine properties of data
Data type (shapefile (shapefile, shapefile, coverage, coverage network dataset, dataset etc) Shape type (point, polygon, line, etc) Spatial reference Extent of f features f List of fields
Logic g can be added to a script p to branch (if ( statement) ) based data properties
Describe
# Describe a feature class d = arcpy.Describe("c:/base.gdb/rivers") # Branch based on the # inputs p ShapeType p yp p property p y if d.shapeType == "Polygon": arcpy.FeatureToLine_management(inFC, outFC) else: l arcpy.CopyFeatures_management(inFC, outFC)
Classes
Most tool parameters can be easily defined
Such as a path or buffer distance
Cursors
Cursors allows
Iteration over the set of rows in a table Ability y to insert new rows into a table Geometry access
At 10
for row in arcpy.SearchCursor(myTable) print row.GetValue(Rank)
Insert Cursor
Cursors support creation of new geometries
# Open an insert cursor for the feature class cur = arcpy.InsertCursor(fc) # Create array and point objects ptList = [arcpy.Point(358331, 5273193), arcpy.Point(358337, 5272830)] lineArray = arcpy.Array(ptList) # Create a new row for the feature class feat = cur.newRow() # Set the geometry of the new feature to the # array of points feat.Shape p = lineArray y # Insert the feature cur.insertRow(feat) # Delete objects del cur, feat
BREAK!
Raster class
Returned output from Spatial Analyst tools
Used to represent a raster dataset on disk C Can be used as inputs p to tools and Sp Spatial Analyst y Map p Algebra expressions
Supports operators (or arithmetic operations in Map Algebra expressions) Has properties and methods for analysis
raster.min raster.max raster.save raster.save() ()
Raster Integration
d party Python library for scientific computing NumPy is a 3rd