Python ArcGIS PowerPoints and Activities
Python ArcGIS PowerPoints and Activities
Geoprocessing in ArcGIS
Basic Programming in ArcGIS with Python
Workshop
RS/GIS Lab, Utah State University
With Material from ESRI
Learning Objectives:
Create a geoprocessing model in ModelBuilder
Export the model as a Python script
Attach a Python script to a tool in ArcToolbox
Become familiar with the PythonWin interface
Right-click on
the tool to get
Properties
dialog, then
choose
Environments
Tab.
General:
Name: must be unique, no
spaces, used in command
line and scripts
Label: need not be unique.
Used for tools display
name.
Description: appears in the
Help Panel.
Stylesheet: controls the
dialogs appearance.
Relative Paths: When set
all path names within the
tool are stored relative to
the toolbox containing the
tool.
Source:
Path to the script file that
will be executed from the
tool
Can be Python, VBScript,
Jscript, AML, and EXE
Points to the script, so if
the script gets updated,
the tool gets updated.
Parameters:
Display Name: label for the
parameter in the dialog
Data Type: type of dataset
Type: defines whether
parameter is required or
optional.
Direction: whether parameter
is input or output
Multi-value: Parameter
handles multiple values.
Default: default value for the
parameter.
Environment: make
parameter display current
env. setting.
Domain: Limits acceptable
values (range & coded)
Dependency: makes one
parameter dependent on
another parameter
Help:
Help documentation that
can be attached to the
tool.
10
Advantages:
Easy to use
ESRI primarily supports Python
Contemporary equivalent of AML
11
PythonWin
Interface:
Menus, toolbars,
and context
menus (windows
look and feel)
Two windows
Script Window:
Write and save
code
Interactive
Window: Test
lines of code, and
report (error)
messages.
Menus:
STEP
AROUND
RUN
SCRIPT
SYNTAX
CHECKER
INTERACTIVE
WINDOW
12
13
10)
11)
12)
13)
14)
15)
16)
17)
18)
19)
20)
21)
22)
23)
24)
25)
26)
27)
28)
29)
30)
12)
13)
14)
15)
16)
17)
If a PythonWin icon is not on the desktop, copy and paste the icon there.
Start PythonWin by double clicking on the PythonWin icon.
Under File choose Open and browse to the Lesson1 folder and open the streamburn.py script.
Well talk about the code, though youre not expected to understand what it all means at this time.
To run the script click on the Run button, or choose Run under File. And see what happens.
The script executes correctly when the message on the bottom bar says returned exit code 0. If it
doesnt say this we have a problem.
Lets change the line that says flowline = flowline, to read flowline = flowline.shp.
Then run the script again.and hopefully it works.
Now open the streamburn_p.py file. This one as arguments which we find in the code (well learn
more about arguments later).
To run this script from PythonWin we provide the arguments in the Run Dialog, separated by a
space.
There are two arguments: the Alternative DEM input, and the name for the output streamburn
grid. We must enter the complete paths for these two arguments separated by a space in the
Arguments entry box of the Run Dialog.
The easiest way to do this is to open ArcCatalog and navigate to the Lesson1 folder, then copy and
paste the pathname to the Arguments entry box, adding the two names we wish to use (e.g.
elev30m100 for the input and fl_burn100 for the output.
We will probably have to edit the line that says flowline = flowline, to read flowline =
flowline.shp again.
Run the script with the arguments and see what happens.
Run the script a second time and see what happens. There should be an error in the Interactive
Windowthe intermediate datasets and the final output datasets already exist.
To fix that well add one more line of code.
After the gp.workspace = C:\\... assignment, add the following line of code:
gp.Overwriteoutput = 1. Then try running the script again. If everything went okay (and the
stars are in the right position), the script executed without a problem.
Lesson 2:
Fundamentals of Python
Basic Programming in ArcGIS with Python
Workshop
RS/GIS Lab, Utah State University
With Material from ESRI
Learning Objectives:
Learn basics of Python syntax
Learn about the importing modules in Python
Learn about the ArcObject concept
Understand the concepts of Properties and Methods
Learn where to find syntax for ArcToolbox tools
Understand why ArcToolbox aliases are important
To be able to edit/write a very simply Python script
fg = "C:\\john\\Lesson2\\fl_grd"
fgPath = C:\\john\Lesson2\\
fg = fl_grd
fullPath = fgPath + \\ + fg
fl = Flowline.shp
fl[0]
# fetches the first item (i.e. F)
fl[1:3] # fetches from 1 up to, but not including, 3 (i.e. lo)
fl[:-4] # fetches from 1 up to, but not including the last
# 4 items ( i.e. Flowline)
num1 = 2.3
num2 = 2 + 3
numList = [1, 2, 3, 4, 5]
grdList = [elev30m, elev30m10, elev30m100, elev30m250]
# create a list
grdList = [elev30m, elev30m10, elev30m100, elev30m250]
# fetch the first item (i.e. elev30m)
grd1 = grdList[0]
# fetch the second item (i.e. elev30m10)
grd2 = grdList[1]
# fetch from first item up to second item
grd3 = grdList[0:1]
# fetch from 1 up to, but not including the last item
grd4 = grdList[0:-1]
# fetch third through the end
grd5 = grdList[2:]
Line Continuation:
Line continuation characters
Backslash \
Parentheses ( ), brackets [ ], and braces { }
Indentation is automatic
# Process: Polyline to Raster...
gp.PolylineToRaster_conversion(flowline, "FID", fl_grd, \
"MAXIMUM_LENGTH", "NONE", "30")
# Create a list
fcList = [streams, rivers, ownership, soils,
roads, springs, hazards]
Python Statements:
importimports a module
import math
import string
import sys, os, arcgisscripting
Other statements:
ifelifelse
while
forin
tryexcept
Notes:
Colons used at end of each condition
Indention defines what executes for each condition
Python automatically indents
One equal sign (=) for assignment, two (==) for conditions
y = 48
# assignment
If y == 48:
# testing a condition
Looping Syntax:
While loops:
y = 1
while y < 15:
print y
y = y + 1
Counted loops:
for y in range (1,15):
print y
List loops
numList = [1, 2, 3, 4, 5]
for num in numList:
print num
Notes:
Colons at end of each condition (implied do this)
Indentation important for proper execution
ArcGIS is
built with
hundreds of
ArcObjects
Map Document
Selection
Layer
Feature Class
Symbol
Table
Field
Row
Map Document
Feature Class
Properties
Properties
-Layer count
-Shape type
-Name
-Spatial reference
-Spatial reference
-Extent
-Map scale
Methods
-Extent
-Create feature
Methods
-Remove feature
-Add layer
-Clear selection
-Select feature
Geoprocessor
Properties
-Current workspace
-Map extent
Env.
Settings
-Cell size
Methods
-Buffer
-Clip
Tools
-Select
-Copy features
-Select feature
To use a method:
Object.Method(arg, arg, )
All methods require parentheses even if there are no arguments
Arguments are separated by commas
gp.Thin_sa(ingrd, thingrd, "ZERO", "NO_FILTER",
"ROUND", "30")
10
Toolbox Aliases:
Many tools in ArcToolbox with
the same name
Toolbox
Alias Name
3D Analyst
3d
Analysis Tools
analysis
Cartography Tools
cartography
Conversion Tools
conversion
Coverage Tools
arc
management
Geocoding Tools
geocoding
lr
sa
Spatial Statistics
stats
Example:
# gp.select_analysis("nfroads.shp", "paved.shp", '
"ROAD_CLASS" = \'PAVED\' ')
Notes:
Fields are double quoted (") and text values are single quoted (')
11
Example:
gp.PolylineToRaster_conversion(InFeatures, "myField", OutRaster,
"MAXIMUM_LENGTH", "","")
Notes:
Can use to skip an optional argument
Example:
gp.Thin_sa(inRaster, outRaster, "ZERO", "NO_FILTER", "ROUND",
30")
Or
gp.Toolbox = sa
gp.Thin (inRaster, outRaster, "ZERO", "NO_FILTER", "ROUND",
30")
Notes:
Can use gp.Toolbox = sa instead of toolbox alias
12
Hint 2: the items in the list loop will look like this [5,10,15]. However this presents
a challenge when you create the output, because each of the output rasters
should have a new name (e.g. slice5, slice10, slice15). The items in the loop are
integers and you cant concatenate an integer to a string, so youll have to convert
the integers to strings. Youll need to import the string module, then list the
functions in the module. From there youll have to find the function that converts
an object (e.g. an integer object) to a string object.
13
4) Open a new Script Window. Click on File > New, then choose Python Script, then click OK.
5) Now copy all the text from the Interactive Window and paste it in the Script Window. Highlight
all the text from the Interactive Window and right-click and choose Copy. Put your cursor in the
top of the Script Window, then right-click and choose Paste.
6) Click the Edit menu and choose Replace. For Find What put >>> and leave Replace with: blank.
Then click the Replace All button. This removes all >>> prompts.
7) The output from what you pasted is flagged with a to the left of it. Delete each of these lines by
backspacing. Then take out the blank character between each remaining line. All the code should
now be flush with the left margin of the Script Window.
8) Go to the Interactive Window, right-click and choose Select All. Then press your delete key. The
Interactive Window should be blank.
9) Save the script by first making the Script Window active by clicking on it (anywhere). Then go
the File menu, and choose Save As. Save the file as lesson2a.py in the Lesson2 folder.
10) Now, run the pythonSyntax.py file by clicking on the Run button, or choosing Run from the File
menu.
11) Highlight all the text in the Script Window, righ-click and choose Source Code, then choose
Comment out region.
12) Now, type the following code:
# working with
x = 25
if x < 25:
print "the
elif x > 25:
print "the
else:
print "the
decision making
number is less than 25"
number is greater than 25"
number is 25"
13) Press the Run button. In Interactive Window you should see the number is 25.
14) Things to remember: if, elif and else must be lowercase, colons must be at the end of each
condition, and Python interprets the indentation as the end of the condition, thus executing the line
of code.
15) Highlight the decision making code and comment it out as before, and save the file (no need to use
Save As this time, just Save).
16) Now, type the following code:
# working with loops
# while loop example
z = 5
while z < 30:
print z
z = z + 5
17) Press Enter twice to end the construct. Save the script file, then press the Run button. You should
see the following values in the Interactive Window: 5 10 15 20 25
18) Highlight the while loop example code, and comment it out as before, and save the script file.
19) Now, type the following code:
# Counted loop example
grdList = ["elev30m", "elev30m10", "elev30m100"]
for eachGrd in grdList:
print eachGrd
20) Press Enter twice to end the construct. Save the script file, then press the Run button. You should
see the following in the Interactive Window:
elev30m
elev30m10
elev30m100
21) Highlight the count loop example code, and comment it out as before, and save the script file.
22) Now, type the following code:
# for loop example
for num in range (2,6):
print num
23) Press Enter twice to end the construct. Save the script file, then press the Run button. You should
see the following values in the Interactive Window: 2 3 4 5
24) Things to remember: while, for, in, and range have to be lowercase. Colons are required at
the end of each while and for statement. Python recognizes the construct as a loop only when it
ends with an indentationcolons and indentations are VERY important in Python!
25) Close the python script File > Close.
2) In PythonWin open a new script window and save it as lesson2b.py in the Lesson2 folder.
3) Type the following comments to start the script.
# Author: John Lowry
# Date: August 17, 2007
# Purpose: Lesson 2b example of a simple python script
5) Set the current workspace as the Lesson2 folder (note your path to the Lesson2 folder may be
different than what is typed below).
# Set the current workspace
gp.workspace = ("C:/john/TeachingGIS/GIS_Programming_with_Python/Lesson2")
6) In ArcToolbox, find the Select tool. If you dont know where it is, use the Search tool. Choose
the Select tool from the Analysis Tools toolbox. Then click on the Locate button.
7) Right-click on the Select tool and choose Help.
8) Scroll down to the Scripting Syntax part, take a look at the table for the parameters and look at the
sample code. Copy and paste the syntax to the Python script window. You may also want to copy
the comment in the sample code. Note were copying all of this because were new at this and I
recommend that when youre leaning its better to have too much comment than to little. Your
code in the script window should look something like this.
# Select Red Butte Creek
# Usage: Select_analysis (in_features, out_feature_class, where_clause)
# For shapefile expression, fields are double quoted (") and text values are
single quoted (')
12) When the script is executed, it tells you the RBCreek.shp already exists. Type the following just
below the gp.workspace line.
gp.overwriteoutput = 1
13) Do the same for the Polygon to Raster toolfind the tool in ArcToolbox, go to Help, and scroll
down to they scripting syntax, then copy and past the syntax as a comment in the script window.
Then write the line of code to execute the tool. Your code should look something like this:
#Convert bufferarea to raster
#PolygonToRaster_conversion (in_features, value_field, out_raster_dataset,
cell_assignment, priority_field, cellsize)
gp.PolygonToRaster_conversion("RBCreekBuff.shp", "FID", "BuffGrd",
"CELL_CENTER", "NONE", "30")
14) Now, were going to change the script so that the buffer distance and units can be passed to the
scripts as arguments (i.e. parameters).
15) First, set the arguments just below where you set the workspace and overwrite properties.
# Argumentsfor buffer distance and buffer units
bufDist = sys.argv[1]
distUnit = sys.argv[2]
16) Import the sys module by adding it to the first line of code in the script.
# Import the arcgisscripting module
import sys, arcgisscripting
17) Comment out the existing buffer_analysis tool, and add the following:
gp.buffer_analysis ("RBCreek.shp", "RBCreekBuff.shp", bufDist+" "+distUnit,
"", "" , "ALL")
18) To make it so that the final output contains the buffer distance in its name, add the variable to the
Polygon to Raster conversion method like this:
gp.PolygonToRaster_conversion("RBCreekBuff.shp", "FID", "BuffGrd"+bufDist,
"CELL_CENTER", "NONE", "30")
19) Finally, its good practice to delete the gp object at the end of the script, so at the very end of the
script enter the following code: del gp.
20) Run the code. Remember youll need to pass the arguments in the Run Script dialog. Each
argument is separated by a space, so you enter something like: 500 feet.
21) Your code should look something like this, and you should have a pretty good idea what it
means
# Author: John Lowry
# Date: August 17, 2007
# Purpose: Lesson 2b example of a simple python sript
#############################################################
# Import the arcgisscripting module
import sys, arcgisscripting
# Create the Geoprocessor object
gp = arcgisscripting.create()
# Set the current workspace & set overwrite on
gp.workspace =
("C:\\john\TeachingGIS\\GIS_Programming_with_Python\\Lesson2")
gp.overwriteoutput = 1
# Arguments for buffer distance and buffer units
bufDist = sys.argv[1]
distUnit = sys.argv[2]
# Select Red Butte Creek
# Select_analysis (in_features, out_feature_class, where_clause)
# For shapefile expression, fields are double quoted (") and text values are
single quoted (')
gp.select_analysis ("flowline.shp", "RBCreek.shp", ' "GNIS_Name" = \'Red
Butte Creek \' ')
# Buffer the selected creek
# Buffer_analysis (in_features, out_feature_class, buffer_distance_or_field,
line_side,
# line_end_type, dissolve_option, dissolve_field)
# gp.buffer_analysis ("RBCreek.shp", "RBCreekBuff.shp", "100 feet")
gp.buffer_analysis ("RBCreek.shp", "RBCreekBuff.shp", bufDist+" "+distUnit,
"", "", "ALL")
#Convert bufferarea to raster
#PolygonToRaster_conversion (in_features, value_field, out_raster_dataset,
cell_assignment, priority_field, cellsize)
gp.PolygonToRaster_conversion("RBCreekBuff.shp", "FID", "BuffGrd"+bufDist,
"CELL_CENTER", "NONE", "30")
del gp
Use a List Loop with the Slice tool to create 3 elevation zone grids for 5, 10 and 15
zones.
Hint 1: Youll need to check out the spatial analysts license
Hint 2: the items in the list loop will look like this [5,10,15]. However this presents a
challenge when you create the output, because each of the output rasters should have a
new name (e.g. slice5, slice10, slice15). The items in the loop are integers and you cant
concatenate an integer to a string, so youll have to convert the integers to strings. Youll
need to import the string module, then list the functions in the module. From there youll
have to find the function that converts an object (e.g. an integer object) to a string object.
import string
dir(string)
print string.digits.__doc__
Lesson 3: Geoprocessing
Programming Model
Basic Programming in ArcGIS with Python
Workshop
RS/GIS Lab, Utah State University
With Material from ESRI
Learning Objectives:
Understand the role of the Geoprocessor (gp) Object
Learn about Properties and Methods of the gp
To be able to interpret the Geoprocessing Programming
Model Diagram
Learn that Properties and Methods return objects and
standard data
Understand why you would want to use a Describe object
To be able to write a simple script using a Describe object
Tool
Method
gp.Buffer_analylsis
Tool
Method
gp.extent
Env. Setting
Property
gp.workspace
Env. Setting
Property
Describe objects
Enumeration objects
Cursor objects
Other objects
The Geoprocessor
Programming Model
Diagram shows all
objects, properties,
methods
Descriptions and
Usage found in
Desktop Help
Property
Read only
Print gp.MessageCount
Read/Write
Print gp.Toolbox
Methods
Gp.AddError(Error)
System toolboxes
available by default
Gp.buffer_analysis()
Addtoolbox method
does not add toolbox
from ArcToolbox, just
makes tools available
for the script
Example of a Method:
Check if data exists with the Exists method
If gp.Exists(flowline.shp):
Print The flowline feature class exists
If not gp.Exists(flowline.shp)
Print The flowline feature class does not exist
Example of a Property:
Overwriteoutput property overwrites existing data
# will overwrite RBCreek.shp if it exists
gp.overwriteoutput = 1
gp.select_analysis ("flowline.shp", "RBCreek.shp", '
"GNIS_Name" = \'Red Butte Creek \' ')
dscDS = gp.describe
print dscDS.Extent
Band count
Etc.
dscRB = gp.describe
print dscRB.Height
Lesson 3b ACTIVITY: Writing a script that creates Describe objects using the Describe
method.
# Author: John Lowry
# Date: August 17, 2007
# Purpose: Lesson 3b: Describing datasets with the Describe Method
#############################################################
# Import the arcgisscripting module
import arcgisscripting
# Create the Geoprocessor object
gp = arcgisscripting.create()
# Set the current workspace & set overwrite on
gp.workspace = ("C:/john/TeachingGIS/ArcGIS_Python/Lesson3_results")
# describing a dataset
dsc = gp.Describe("landcover")
print "The data type is: " + dsc.DataType
#print dsc.SpatialReference
print "The spatial reference is:" + dsc.SpatialReference.Name
# doing something based on a decision
if dsc.DataType == "RasterDataset":
print "The cell size is: " + str(dsc.MeanCellHeight)
else:
print "not a raster dataset"
del gp
del dsc
Lesson 4:
Enumeration & Cursor Objects
(with some coding tips)
Basic Programming in ArcGIS with Python
Workshop
RS/GIS Lab, Utah State University
With Material from ESRI
Learning Objectives:
To understand uses of enumeration objects
To be able to write a simple script using enumeration
To understand uses of cursor objets
To be able to write a simple script using cursors
To nderstand some basic debugging and coding guidelines
To review how scripts are added to ArcToolbox
Enumeration objects:
A list of data (any type) without a known count
ListFields returns a Fields object
ListIndex returns a Indexes object
All other Enumeration methods return an Enumeration object
SearchCursor object:
To find out the value of a field for individual row (row), use:
Fieldname (a property)
Print row.GNIS_Name
Or
- GetValue (fieldName) (a method)
Print row.GetValue(GNIS_Name)
SearchCursor example:
gp.workspace = (C:/john/Lesson4)
cur = gp.SearchCursor (nests1990)
row = cur.Next()
while row <> None:
print row.nestsiteid
print row.condition
row = cur.Next()
del cur
Notes:
- Because row is not a string, but an object, we use None for the conditional
-
UpdateCursor object:
UpdateCursor example:
gp.workspace = (C:/john/Lesson4)
cur = gp.UpdateCursor (nests1990, nestsiteid > 5)
row = cur.Next()
while row:
row.condition = string.replace(row.condition, poor, good)
cur.UpdateRow(row)
row = cur.Next()
del cur
Notes:
- This code: Begins with the first row that has a
nestsiteid > 5, replaces condition that is poor
with good for each row, finally updates the row
change.
- The string.replace method requires the
string module be imported (not shown in code).
- We delete the cursor object at end of the while
construct (to free the variable & memory).
InsertCursor object:
InsertCursor example:
gp.workspace = (C:/john/Lesson4)
cur = gp.InsertCursor (nestdata1990.dbf)
row = cur.NewRow()
row.nestsiteid = 11
row.height =90
row.count = 3
cur.InsertRow(row)
Notes:
- This code: Inserts a new row to the table
nestdata1990.dbf and fills the nestsiteid,
height and count fields.
- Once all the the values are populated, the row is
inserted into the table.
- If this were a feature class, the shape field
would have to be added as well.
Coding Guidelines
-
If a script has arguments, you should have code that checks the inputs have
been given by the user (when attaching script in ArcToolbox we can provide
a default input).
Use comments (over commenting your own scripts, esp. when youre
beginning is not a bad idea).
Include a header to each script telling the scripts name, a little about how it
works, its requirements, who wrote it and when it was written.
Other guidelines?
10
The objective of the script is to create a viewshed for each nest site.
We will use a cursor object to loop through all of the nest sites in the point
feature dataset: As we loop through we will select out each point (Select tool), run
the Viewshed tool for that point, and then do the same for the next point.
Finally, we want to give the script two arguments: a workspace argument, so the
script can be run in any user defined workspace, and second, a dataset argument,
so the script can be run on any user defined nest site dataset.