You are on page 1of 59

Lesson 1:

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

Lesson 1a: Creating as Simple Model


Creating a new custom toolbox or adding an
existing custom toolbox in Arc Map:
Right-click ArcToolbox
Give the toolbox a name
Toolbox appears in alphabetical order (tip:
give a name starting with Z)
Toolbox is a file with extension .tbx that by
default is placed:
C:\Documents and Settings\jlowry\Application
Data\ESRI\ArcToolbox\My Toolboxes

Creating a new model or adding an existing


model to the toolbox:
Models (and scripts) can be
organized within Toolsets or
placed directly in the toolbox as
tools

Creating a New Model:


Give the model a meaningful
name
Use Edit to open the
ModelBuilder Window.

Drag and drop geoprocessing tools from


ArcToolbox to window:

Double-click the geoprocessing tool to input the


tool parameters:

Colored symbols means process is ready to run.


Blue ovals = input, yellow box = tool, green oval =
output.

Element properties: Right-click on output oval


example:
Open same as double-clickingchange
name or location of output.
Model Parameter Make the output ( or
input (blue oval)) a parameter.
Add to Display when the element is
created, add to the display.
Intermediateflag as an intermediate
dataset, and delete from Model menu.
Create Label Create a text label
describing the element.

The Model Menu:


Run run selected tool in the model.
Also, Run Entire Model and Validate
Entire Model.
Savesave the model (good idea to
save often, and make backup copies if
its a large model).
Delete Intermediate Datadeletes all
data flagged as intermediate.
Export to Python, Jscript, or VBscript.
Importa Arcview 3.3. model.

Buttons in the ModelBuilder Window:

Model Properties: Right-click on model


General: assign model name,
label, description and alias name
Parameters: input parameters
for the model, and order of input
Environments: environment
settings such as Raster Mask,
Raster Cell Size, etc.
Help: Provide a help document
to your model
Iteration: Run the model multiple
times (batch)

Environment Settings can be applied for the whole


model or single tool in the model:
Right-click model within the
Toolbox to get Properties dialog,
then choose Environments Tab.

Right-click on
the tool to get
Properties
dialog, then
choose
Environments
Tab.

Setting parameters for certain elements (variables)


in your model make the model more flexible:
Right-click on the element and
check on Model Parameter.
Right-click on
the tool to get
Properties
dialog, then
choose
Environments
Tab.

So when you double-click on the


model, or Open the model you will
be asked for input parameters.

ACTIVITY: Creating a simple Model


As a class well create a simple geoprocessing model.
The model will facilitate making a stream burn grid, and will
require four geoprocessing tools:
Polyline to raster (conversion toolbox)
Setnull (spatial analyst toolbox)
Thin (spatial analyst toolbox)
Con (i.e. conditional statement, from spatial analyst toolbox)
Data inputs will be a vector stream shapefile, and three elevation
grids: elev_30m, elev_30m-10, and elev30m-100
Well make and run the model first without parameters, then well
make a copy of it and add parameters to the copy.
Finally well run both and see how they differ.

Lesson 1b: Running a Python Script from


ArcToolbox
Need to attach the script as a
tool in a toolbox.
Need to set the properties of
the tool and link to the script.
Advantages:
Can be incorporated into a
model
Run from command line
Assign help documentation
User interface with buttons
Dialog prevents errors
Data type checking
Data existence checking
Can use Domains &
Dependencies

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

ACTIVITY: Attaching a script to a tool.


As a class well export the 2 models we created in Lesson1a to 2
scripts
Well fill in the properties for the 2 script tools, and run them from
ArcToolbox
Well note the difference between having parameters and not
having parameters for the script
Well note the difference between using Open and Edit to look at
the tools

Lesson 1c: Introduction to PythonWin


What is Python?
An open-source, object-oriented, scripting language
Python files are text files (.py extension)
Several Integrated Development Environments (IDE)
available for editing/writing python scripts
E.g. PythonWin, Python IDLE, Crimson editors
Were using PythonWin 2.4.1

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.

Debugging & Standard Toolbars


STEP
THROUGH

Menus:
STEP
AROUND

RUN
SCRIPT

SYNTAX
CHECKER

INTERACTIVE
WINDOW

Run script dialog


-With or w/out Arguments (Parameters)
-No debugging or debugging

File: open, new, save,


run
Edit: find, replace,
undo, select all,
gotoline
View: toolbars>
standard &
debugging.
options>line
numbering
Tools, Window and
Help
Means script ran
successfully

12

Context menu allows commenting/uncommenting regions of code

ACTIVITY: Running a script in PythonWin


As a class well:
In PythonWin, well open the two scripts we exported to Python
Examine the code to try to understand what it means
Run the scripts and edit them as necessary to make them run
properly

13

Lesson 1: Geoprocessing in ArcGIS


Lesson 1a ACTIVITY: Creating a simple Model
1)
2)
3)
4)
5)
6)
7)
8)
9)

10)
11)
12)
13)
14)

15)
16)
17)

18)
19)
20)
21)

22)
23)
24)
25)

26)
27)
28)

29)
30)

Open ArcCatalog and navigate to the Lesson1 folder.


While in the Contents tab, right-click in the window and choose New, then choose Toolbox.
Rename the new toolbox Z_lesson1.
Double-click on Lesson1.mxd to open it in ArcMap.
In the AcToolbox window, right-click on ArcToolbox and choose Add Toolbox.
Right-click on the Z_Lesson1 toolbox and choose New, then choose Model.
In the Conversion Tools toolbox, find the To Raster toolset and drag the Polyline to Raster tool to
the ModelBuilder window.
Double-click on the Polyline to Raster tool in the ModelBuilder window.
For Input Features choose flowline.shp, for Value field leave as FID, for Output Raster put fl_grd
(note the path for the output raster should be to the Lesson1 folder). Change the Cellsize to 30,
and leave the other inputs as default. When done, click OK.
At the top of the ModelBuilder window, click on the Auto Layout button, then click on the Full
Extent button.
From the Model menu, click on Save.
Close the Conversion Tools toolbox, and open the Spatial Analysts Tools toolbox.
From the Conditional toolset, drag and drop the Set Null tool to the window.
For the Input conditional raster choose fl_grd, for Input false raster or constant value, put 1.
Name the output raster fl_nodata, and for the Expression put VALUE < 0. When done, click the
OK button.
To find the Thin took, click on the Search tab within the ArcToolbox window, and type in the
work thin, then click the Search button.
Drag the Thin tool from the Spatial Analyst Toolbox to the Modelbuilder Window.
Double-click on the Thin tool and fill in the input parameters as follows. Use fl_nodata for the
input raster, call the output raster fl_thin, Maximum thickness put 30, and for everything else use
the defaults. Click OK.
At the top of the ModelBuilder window, click on the Auto Layout button, then click on the Full
Extent button.
From the Model menu, click on Save.
Finally, from the Conditional toolset, drag and drop the Con tool to the window.
For the Input conditional raster choose fl_thin, for the Input true raster or constant value choose
elev30m-10, for Input false or constant value put elev30m, name the output raster fl_burn10, for
Expression put VALUE=1. Click OK.
At the top of the ModelBuilder window, click on the Auto Layout button, then click on the Full
Extent button.
From the Model menu, click on Save. Then from the Model menu click on Close. Save again, if
it asks you to.
Right-click on the model and rename it streamburn.
Right-click on the streamburn model and choose Properties. Click on the Environments tab and
open General Settings and click on Extent, then click on Values. Then click on General Settings
and for the Extent choose the elev30m dataset to specify the extent (otherwise the final output of
the model will be the extent of the streams which is smaller than the entire elevation grid). Then
click on Current Workspace, click on Values and set the current workspace to the Lesson1 folder.
Right-click on the streamburn model and choose Edit, this opens the model again.
Right click on all the green ovals and make sure they are checked on for Intermediate and Add to
Display (note you could click Intermediate off for the last output if you wish).
From the Model menu choose Run Entire Model. You should see all 4 steps of the model run, and
the intermediate datasets added to ArcMap. Close the model (Model > Close), and examine the
new data layers added to the ArcMap.
Right-click the streamburn model, and choose Copy.
Right-click the Z_Lesson1 Toolbox, and choose Paste.

31) Rename the copied model streamburn_p.


32) Right-click on the streamburn_p model and choose Edit.
33) Right-click on the blue oval for the Con tool that says elev30m-10 (this grid assigns the grid
values where the Thin grid = 1, in other words the elevation minus 10 meters).
34) Check on a Model Parameter for this input.
35) Since the input is now a parameter, we also want to have control over what we name the output, so
right-click the output green oval for the Con took and make it a parameter as well.
36) Save the model, and close.
37) Now double-click (also right-click Open) on the streamburn_p model and you will see that the
default input parameters are there, but you can also change them easily. Instead of elev30m-10,
use the elev30m-100 (100 meter burn). And change the output name to fl_burn100. Then click
OK to run the model.
38) Zoom in and you should see that the fl_burn100 is quite different from the fl_burn10. You can
also test this with the identify button with the Identify from: set to <All layers> instead of the
<Top-most layer>, which is the default.
39) Finally, double-click on the streamburn model (one with out parameters). What happens? Can
you see how setting parameters can be useful?
40) Exit ArcMap, but before you do remove any of the datalayers created in this Activity (e.g. fl_grd,
fl_nodata, fl_thin, fl_burn10, etc.), then delete them from the Lesson1 folder using ArcCatalog.

Lesson 1b ACTIVITY: Running a Python Script from ArcToolbox


1) First, export the models we created from Lesson1a to Python scripts. Start the ModelBuilder
window for both the streamburn and streamburn_p models by right-clicking on the model and
choosing Edit. Under the Model menu, choose Export, and then export the model to a Python
script. Create streamburn.py and streamburn_p.py, and make sure theyre both in the Lesson1
folder.
2) Right-click on the Z_Lesson1 toolbox, and choose Add, then choose Script.
3) Right-click on the Script tool and choose Properties.
4) On the General tab, enter streamburn for the Name, Streamburn No Parameters for the Label, and
a short description for the Description. Click on Store relative path names.
5) On the Source tab, link to the tool to the streamburn.py file.
6) Click on the Parameters tab and dont do anything (this file has no parameters), then click OK.
7) Add the streamburn_p.py script in the same way as steps (2-3).
8) Open the Properties and click he General tab. Enter streamburn_p for the Name, Streamburn With
Parameters for the Label, and a short description for the Description. Click on Store relative path
names.
9) Click on the Parameters tab and then click on the blank cell just below Display Name. For this
parameter enter something like DEM subtracted. To the right of that cell, select Raster Layer
from the dropdown list for the Data Type.
10) For the Parameter Properties, leave it as Type=Required, Direction=Input, and MuliValue=No.
11) Click on the blank cell below the Display Name DEM subtracted and enter Streamburn
Output.
12) For the Parameter Properties, change Direction=Output.
13) Click OK.
14) Click on the Streamburn No Parameters script tool ( or alternatively right-click and choose
Open). Click OK. The script should run correctly, but nothing gets added to the ArcMap
Display.
15) Click on the Streamburn With Parameters script tool. Choose the elev30m1100 grid as the
Alternate DEM and call the output grid fl_burn100. Run the script and see what happens.
16) NOTES: If you wanted to share these script and model tools with someone (or move them to
another location) you would give them the Z_Lesson1.tbx file and the .py files. Since the scripts
are stored with relative paths, they should work as long as the .py files remain in the same location
relative to the .tbx file.

Lesson 1c ACTIVITY: Introduction to PythonWin


1)
2)
3)
4)
5)
6)
7)
8)
9)
10)
11)

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

Lesson 2a: The Basics of Python Syntax


Comment: non-executable line of code
One or two number signs (# or ##)
# Set the current workspace
gp.workspace = "C:\\john\\Lesson2
## Set so output can be overwritten
gp.Overwriteoutput = 1

Comment and uncomment blocks of code


Right-click the line of code > Source Code >
Comment out region
Useful for debugging code

Variable: a named entity that holds information


Can hold different types of data
Strings, numbers, lists, tuples, dictionaries, files
# Local variables...
fg = "C:\\john\\Lesson2\\fl_grd"

No declaration key word or type assignment, Python smart enough


to know fg holds a string
Variables are case sensitive (below are two different variables):
Num = 1000
num = 2000

Strings: text or characters

Strings surrounded by double () or single () quotes

Pathnames use two back (\\) or one forward (/) slash

fg = "C:\\john\\Lesson2\\fl_grd"

Strings can be concatenated (combined together) with + character

fgPath = C:\\john\Lesson2\\
fg = fl_grd
fullPath = fgPath + \\ + fg

Strings are indexed (you can fetch characters/items)

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)

Numbers and Lists:

Variables can hold numbers and expressions

num1 = 2.3
num2 = 2 + 3

Variables can hold lists

numList = [1, 2, 3, 4, 5]
grdList = [elev30m, elev30m10, elev30m100, elev30m250]

Lists are indexed

# 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:]

Variable Naming Conventions (ESRI):


Use combination of lower and upper case, beginning
with lowercase
Acronym at the beginning, use lowercase, followed by
descriptive part with uppercase
fcFlowline = flowline.shp
grdElev = sys.arg[3]

Avoid special characters (e.g. / \ & * !)


Examples of no-so-good variable names
Var1, a, temp-var, b

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]

Built-in Python Functions:


len( ) returns the length of a string or a list
fc = flowline.shp
len(fc) returns 12
grdList = [elev30m, elev30m10, elev30m100]
Len(grdList) returns 3

round ( ) returns a rounded number


xCoord = 435690.435676
round(xCoord) returns 435690

max ( ) returns the maximum value


xExtent = (435690, 455700)
Max(xExtent) returns 455700

Importing Modules for Additional Functions:


The math module:
import math
math.sqrt(49) returns 7
math.pow(10,2) returns 100

The string module:


import string
string.split (4 5 9 13) returns [4, 5, 9, 13]
string.upper (c:\\john) returns C:\\JOHN

Other Python modules:


sys, os, arcgisscripting, gdal

Python Statements:
importimports a module
import math
import string
import sys, os, arcgisscripting

printprints to the Interactive Window


print buffer done!
print dataset does not exist

Other statements:
ifelifelse
while
forin
tryexcept

Decision Making Syntax:


Testing conditions
if y == 1:
print y is 1
elif y == 2:
print y is 2
else:
print y is neither 1 nor 2

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

ACTIVITY: Learning Python Syntax


As a class well:
Experiment with what weve learned about Python syntax.
Well start in the Interactive Window, then move to writing simple
scripts in the Script Window

Lesson 2b: Accessing Tools and


Environment Settings
Application

ArcGIS is
built with
hundreds of
ArcObjects

Map Document
Selection
Layer

Feature Class

Symbol

Table

Field

Row

Interacting with ArcObjects (Object Oriented


Programming)
Each ArcObject has
Properties and Methods
Property: Characteristic of
an object
Method: Something the
object knows how to do
(action)

We interact with objects


through properties and
methods

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

The Geoprocessor ArcObject:


Most geoprocessing sits
on one ArcObject called
the Geoprocessor Object
The geoprocessor object
has many properties and
methods

Geoprocessor
Properties
-Current workspace
-Map extent

Env.
Settings

-Cell size
Methods
-Buffer
-Clip

Tools

-Select
-Copy features
-Select feature

Accessing the Geoprocessor with Python:

The gp object can be used in many languages


Perl, VBScript, Jscript, Python, VBA, VB, etc.
Any COM (Component Object Model) compliant language

In Python, objects are accessed through dot notation


# Import the arcgisscripting module
import arcgisscripting
# Create the Geoprocessor object (assign gp varible name)
gp = arcgisscripting.create()

Thereafter all geoprocessing functionality is accessed through the gp


object (or gp variable)
# Check out the spatial analyst extension license
gp.CheckOutExtension("spatial")

Syntax for properties and methods:


To assign a value to a property:
Object.Property = Value
gp.Workspace = C:\\john\Lesson2

To get a value of a property:


Object.Property
Print The workspace is + gp.Workspace

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")

Finding Scripting Syntax for Environment Settings


or Tools:
ArcGIS Desktop Help:
Contents > Geoprocessing tool reference
Index and Search Tabs

In ArcToolbox (my preferred method):


Right-click tool, then choose Help

Usage in Python (in Interactive Window), type:


gp = arcgisscripting.create()
gp.Usage("Thin_sa")
'Usage: Thin_sa <in_raster> <out_raster> {ZERO | NODATA}
{NO_FILTER | FILTER} {ROUND | SHARP} {maximum_thickness}'

10

Toolbox Aliases:
Many tools in ArcToolbox with
the same name

Toolbox

Alias Name

3D Analyst

3d

Analysis Tools

analysis

Cartography Tools

cartography

Coverage Tools > Analysis >


Clip

Conversion Tools

conversion

Coverage Tools

arc

Analysis Tools > Extract > Clip

Data Management Tools

management

Geocoding Tools

geocoding

Linear Referencing Tools

lr

Spatial Analyst Tools

sa

Spatial Statistics

stats

Always suffix the tool with the


toolbox alias name
Always assign alias names to
custom toolboxes

Usage: Thin_sa <in_raster> <out_raster> {ZERO | NODATA}


{NO_FILTER | FILTER} {ROUND | SHARP} {maximum_thickness}

Example: The Select Tool


Syntax:
Select_analysis (in_features, out_feature_class, where_clause)

Example:
# gp.select_analysis("nfroads.shp", "paved.shp", '
"ROAD_CLASS" = \'PAVED\' ')

Notes:
Fields are double quoted (") and text values are single quoted (')

11

Example: The Polyline to Raster Tool


Syntax:
PolylineToRaster_conversion (in_features, value_field, out_raster_dataset,
cell_assignment, priority_field, cellsize)

Example:
gp.PolylineToRaster_conversion(InFeatures, "myField", OutRaster,
"MAXIMUM_LENGTH", "","")

Notes:
Can use to skip an optional argument

Example: TheThin Tool


Syntax:
Thin_sa (in_raster, out_raster, background_value, filter, corners, maximum_thickness)

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

ACTIVITY: Write a Python Script as a Class


As a class well:
Write a small geoprocessing script
Find the syntax for three geoprocessing tools and include them in the script
Run the geoprocessing script from PythonWin

CHALLENGE: Write a Python Script in Teams


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 to use Slice.
# check out spatial analyst license
gp.CheckoutExtension("spatial")

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

Lesson 2: Fundamentals of Python


Lesson 2a ACTIVITY: Learning Python Syntax
1) Well begin by entering Python code in the Interactive Window.
2) The >>> is the PythonWin prompt. Do not type >>>. After typing, press Enter and see what is
returned.
3) This is what we did in class (text after the prompt is what we typed, text without a prompt is what
was returned).
>>> # Lesson 2a--working with Python syntax in the Interactive Window
>>> # John Lowry
>>> # Aug. 14, 2007
>>> ##################################################################
>>> # Working with variables
>>> boy = "Jim"
>>> print boy
Jim
>>> a = 2 + 4
>>> print a
6
>>> boyList = ["Jim", "John", "Andy", "Frank"]
>>> print boyList[0]
Jim
>>> print boyList[2]
Andy
>>> print boyList[-1]
Frank
>>> shpName = "Streams.shp"
>>> print shpName[:-4]
Streams
>>> # Working with built-in functions
>>> print round(9.2333)
9.0
>>> # Importing a new module
>>> import math
>>> # Find out what functions come with the math module
>>> dir(math)
['__doc__', '__name__', 'acos', 'asin', 'atan', 'atan2', 'ceil', 'cos',
'cosh', 'degrees', 'e', 'exp', 'fabs', 'floor', 'fmod', 'frexp', 'hypot',
'ldexp', 'log', 'log10', 'modf', 'pi', 'pow', 'radians', 'sin', 'sinh',
'sqrt', 'tan', 'tanh']
>>> # Look at the documentation for the log function in the math module
>>> print math.log.__doc__
log(x[, base]) -> the logarithm of x to the given base.
If the base not specified, returns the natural logarithm (base e) of x.
>>> # Import the string module
>>> import string
>>> string.capitalize("HELLO")
'Hello'
>>> # Example of Concatenating strings
>>> a = "streams"
>>> p = ".shp"
>>> print a + p
streams.shp
>>> filename = string.capitalize(a[0])+ a[1:] + p
>>> print filename
Streams.shp

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.

Lesson 2b ACTIVITY: Writing a Simple Python Script


1) Open the Lesson2b.mxd and look at the flowline layer.

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

4) Import the arcgisscripting module and create the gp object.


# Import the arcgisscripting module
import arcgisscripting
# Create the Geoprocessor object
gp = arcgisscripting.create()

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 (')

9) Type in the code for the Select_analysis tool.


gp.select_analysis ("flowline.shp", "RBCreek.shp", ' "GNIS_Name" = \'Red
Butte Creek \' ')

10) Save the code and run the script.


11) Now, do the same for the Buffer tool from the analysis toolboxfind 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:
# 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")

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

Lesson 2b CHALLANGE: Write a Python Script that does the following:


a.
b.
c.

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__

Your script should look something like this:


# Author: John Lowry
# Date: August 17, 2007
# Purpose: Lesson 2b example of a simple python sript
# Challenge: convert integer variable to string and use list loop
#############################################################
# Import the arcgisscripting module
import sys, arcgisscripting
# Create the Geoprocessor object
gp = arcgisscripting.create()
# check out spatial analyst license
gp.CheckoutExtension("spatial")
# Set the current workspace & set overwrite on
gp.workspace = ("C:\\john\TeachingGIS\\GIS_Programming_with_Python\\Lesson2")
gp.overwriteoutput = 1
# set up list loop for Slice tool
# Slice_sa (in_raster, out_raster, number_zones, slice_type, base_output_zone)
zoneList = [5,10,15]
for zone in zoneList:
zonestr = str(zone)
gp.slice_sa("elev30m", "slice"+zonestr, zone)
print "creating sliced grid for zone "+zonestr+" zones"
del gp

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

Lesson 3a: The Geoprocessor (gp) Object


The Geoprocessor is an object (special variable) that
has properties and methods
All tools are methods
All environmental settings are properties

We access the methods and properties through the gp


object
gp.Thin_sa

Tool

Method

gp.Buffer_analylsis

Tool

Method

gp.extent

Env. Setting

Property

gp.workspace

Env. Setting

Property

The Geoprocessor has properties and methods that are


NOT environmental settings or tools
gp.Toolbox
gp.Usage
gp.Exists

There are other scripting objects besides the gp

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)

Each box represents and object


Objects grouped by functionality (colors)
All objects sit on the geoprocessing object

All tools and environment setting not listed in


the diagram
All can be called from the Geoprocessor
Tools and env. settings depend on whats
available (e.g. what toolbox has been added)

System toolboxes
available by default
Gp.buffer_analysis()

If you call a tool from


custom toolbox you
must add it.
Gp.Addtoolbox
(C:/john/Z_lesson.tbx)

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 \' ')

Lesson 3a ACTIVITY: Write a script using the


Exists method and the Overwriteoutput property
In teams, write a short script that does the
following:
Checks the current workspace (Lesson3) for a dataset called
landcover.
If the dataset exists then use the Copy Raster tool (Data
Management) to make a backup copy called landcover_bak

Lesson 3b: Using Describe Objects


Properties and methods return either standard data or objects
Most return standard data (a string or number (sometimes a
boolean))
Exists(InputValue): Boolean, returns 1 or 0 and can be used in an If
statement:
If gp.Exists(C:/john/flowline.shp):
print The feature class exists

Some return an object


Describe(IntputValue): Object, returns an new object
dscDS = gp.Describe (C:/john/flowline.shp)
print dscDS.Extent

In the model diagram:


Type of data returned by property or method on right of colon
If not indicated, a string or numeric data is returned.

The Describe method on the geoprocessor object returns an


object (a describe object)
The type of describe object returned, depends on the type data
described (feature class, table, raster dataset, etc.)
All describe objects provide descriptive information about the
data being described
Extent
Spatial reference
Coverage tolerances
Cell size

dscDS = gp.describe
print dscDS.Extent

Band count
Etc.

dscRB = gp.describe
print dscRB.Height

Help for the Describe Method from ArcGIS Desktop Help


Contents Tab > Geoprocessing > Automating your work with
scripts > Scripting object: Properties and Methods> Describe
method

Lesson 3b ACTIVITY: Create Describe objects


using the Describe method
As a class, use the model diagram to answer the
following questions:
After the Describe method, what method would be
used to find out the Type of dataset were looking at?
What about the Spatial Reference name?
How could we determine the cell size of a raster
dataset?

As a class well write a script that does this.

Lesson 3: The Geoprocessing Model


Lesson 3a ACTIVITY: Write a script using the Exists method and the Overwriteoutput
property.
# Author: John Lowry
# Date: August 17, 2007
# Purpose: Lesson 3a: Describing datasets with the Exists 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")
gp.overwriteoutput = 1
# check the current workspace for a dataset called "landcover"
# make a backup copy if it exists
if gp.Exists("landcover"):
gp.CopyRaster_management("landcover", "landcover_bak")
else:
print "dataset doesn't exist"
del gp

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

Lesson 4a: Enumeration Methods & Objects


Enumeration
methods:
Sit on the geoprocessor
object
Each returns an object
Each object holds a list of
data
Object returned depends
on the method called

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

The Enumeration object:


Has two methods: Next and Reset

Next returns the name of an item in the enumeration object (list)


Reset returns to the item as the start of the list

An Enumeration object example: ListRasters(wildcard, rasterType)

# workspace must be set!!


gp.workspace = (C:/john/Lesson4)
# get a list of grids beginning with elev
rasList = gp.ListRasters(elev*, GRID)
# loop through list and print items in list
ras = rasList.next()
while ras:
print ras
ras = rasList.next
# reset ras to top of list
ras = rasList.reset()

The ListFields (InputValue, wildCard, fieldtype) example:


ListFields returns the Fields object
Next returns the Field object
The Field object returns the Name

fldList = gp.ListFields(flowline, *, String)


fld = fldList.Next()
While fld <> None:
Print fld.Name
fld = fldList.Next()

Lesson 4a ACTIVITY: Complete the Code


As a class, using Desktop Help and the model diagram write the
code:
List all the .dbf files in a workspace that begin with 1990
90dbfList = gp.ListTables(1990*, dBASE)

List all the CAD files in a workspace that begin with rd


cmpCADList = gp.ListDatasets(rd*, CAD)

List all the tools from the conversion toolbox


conToolList = gp.ListTools(*_conversion)

Lesson 4b: Cursor Methods & Objects


Cursor methods access attributes/values in table cells:
Sit on the geoprocessor object
Each returns an object (an enumeration/list of row objects)
Cursors work with rows in a table or feature class
Add and delete rows
Read values in rows
Modify values in rows

Cursor Methods return Cursor Objects:

InsertCursor returns the InsertCursor object

Used to insert new rows


SearchCursor returns the SearchCursor object

Used to read values in a row


UpdateCursor returns the UpdateCursor object
Used to make changes to values in rows, and delete rows

SearchCursor object:

Next returns an individual row 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)

Reset takes you back to the start of the cursor

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
-

We could also have use the GetValue method


print row.GetValue(netsiteid)
print row.GetValue(condition)

We delete the cursor object at end of the while construct

UpdateCursor object:

Next returns an individual row object


To find out the value of a field for individual row (row), use:
Fieldname Reads/writes a value from/to a field
- GetValue (fieldName) Reads a value from a field
- SetValue (fieldName, Value) Writes a value to a field
UpdateRow passes modified row into the table/feature class
DeleteRow deletes a row

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:

NewRow creates a new row object


Fieldname Reads/writes a value from/to a field
- GetValue (fieldName) Reads a value from a field
- SetValue (fieldName, Value) Writes a value to a field
InsertRow inserts the row into the table or feature class
Automatically fills the OID field

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.

Geometry Object and example:


gp.workspace = (C:/john/Lesson4)
cur = gp.SearchCursor (flowline)
row = cur.Next()
while row:
geom = row.Shape
print geom.Length
row = cur.Next()
del cur

Lesson 4b ACTIVITY: Write a script using


cursor methods and objects.
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.

Debugging and Coding Tips


Test code in PythonWin, not ArcToolbox
Check Python syntax in PythonWin with Check button
Dont forget arguments (if you have them)
Check error message in Interactive Window
Try to understand the code
Narrow errors to a block or line of code (using
commenting)

Coding Guidelines
-

Use consistent variable naming conventions (e.g. myIntegerVar = 1)

Script names should follow similar naming conventions (e.g. mySript.py)

Use indentation to show structure (Python enforces this).

Use arguments in a script

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

Lesson 4: Enumerations and Cursors


Lesson 4a ACTIVITY: Complete the code.
List all the .dbf files in a workspace that begin with 1990
90dbfList = gp.ListTables(1990*, dBASE)
List all the CAD files in a workspace that begin with rd
cmpCADList = gp.ListDatasets(rd*, CAD)
List all the tools from the conversion toolbox
conToolList = gp.ListTools(*_conversion)

Lesson 4b ACTIVITY: Write a script using cursor methods and objects.

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.

Below are 4 progressively flushed-out iterations of a script written to meet the


objectives of this activity. Note, I first start out simply trying to get the Cursor loop to
work (script 1), when I get the cursor loop to work, I add the first geoprocessing step to
the loop (script 2), when thats working I add another geoprocessing step to the loop
(script 3). Finally, I add my arguments so I can run the tool in ArcToolbox with
parameters, and I add messages the script user will see.

# Author: John Lowry


# Date: August 17, 2007
# Purpose: Lesson 4b1: Using cursors script
# FIRST SET UP THE BASICS AND GET THE CURSOR LOOP WORKING
#############################################################
# Import the arcgisscripting module
import sys, arcgisscripting
# Create the Geoprocessor object
gp = arcgisscripting.create()
# Set the workspace
gp.workspace = ("C:\john\TeachingGIS\ArcGIS_Python\Lesson4_results")
##if gp.Exists("nests1990.shp"):
##
print "the shapefile exists"
# Set up cursor object
cur = gp.SearchCursor("nests1990.shp")
row = cur.Next()
while row <> None:
print row.nestsiteid
row = cur.Next()
del cur
del gp

# Author: John Lowry


# Date: August 17, 2007
# Purpose: Lesson 4b2: Using cursors script
# NEXT, GET THE SELECT TOOL TO WORK IN THE CURSOR LOOP
#############################################################
# Import the arcgisscripting module
import sys, arcgisscripting
# Create the Geoprocessor object
gp = arcgisscripting.create()
gp.overwriteoutput = 1 # ADDED THIS TO HELP IN THE DEBUGGING
# check out spatial anlayst extension
gp.checkoutextension("spatial")
# Set the workspace
gp.workspace = ("C:\john\TeachingGIS\ArcGIS_Python\Lesson4_results")
# Set up cursor
cur = gp.SearchCursor("nests1990.shp")
row = cur.Next()
while row <> None:
i = str(row.nestsiteid) # NEED TO MAKE THIS A STRING
print i
#Select_analysis <in_features> <out_feature_class> {where_clause}
#note line conintuation \ character
gp.Select_analysis("nests1990.shp", "tmp"+i+".shp", \
"\"nestsiteid\" = "+i+"")
row = cur.Next()
del cur
del gp

# Author: John Lowry


# Date: August 17, 2007
# Purpose: Lesson 4b3: Using cursors script
# NEXT, ADD MORE GEOPROCESSING STEPS (E.G. VIEWSHED) TO THE LOOP
#############################################################
# Import the arcgisscripting module
import sys, arcgisscripting
# Create the Geoprocessor object
gp = arcgisscripting.create()
gp.overwriteoutput = 1
# check out spatial anlayst extension
gp.checkoutextension("spatial")
# Set the workspace
gp.workspace = ("C:\john\TeachingGIS\ArcGIS_Python\Lesson4_results")
# Set up cursor
cur = gp.SearchCursor("nests1990.shp")
row = cur.Next()
while row <> None:
i = str(row.nestsiteid)
print i
#Select_analysis <in_features> <out_feature_class> {where_clause}
#note line continuation \ character
gp.Select_analysis("nests1990.shp", "tmp"+i+".shp", \
"\"nestsiteid\" = "+i+"")
# Viewshed_sa (in_raster, in_observer_features, out_raster,
# z_factor, curvature_correction, refractivity_coefficient)
gp.ViewShed_sa ("elev30m", "tmp"+i+".shp", "tmpras"+i,"" ,"" ,"" )
row = cur.Next()
del cur
del gp

# Author: John Lowry


# Date: August 17, 2007
# Purpose: Lesson 4b3: Using cursors script
# FINALLY, ADD ARGUMENTS FOR WORKSPACE AND DATASET, ADD ERROR
# CHECKING AND MESSAGES
#############################################################
# Import the arcgisscripting module
import sys, arcgisscripting #ADD SYS MODULE FOR ARGUMENTS
# Create the Geoprocessor object
gp = arcgisscripting.create()
gp.overwriteoutput = 1
# check out spatial anlayst extension
gp.checkoutextension("spatial")
wks = sys.argv[1]
data = sys.argv[2]
# Set the workspace
gp.workspace = wks # REPLACED WITH WORKSPACE VARIABLE
# Set up cursor
cur = gp.SearchCursor(data) #REPLACED WITH DATA VARAIBALE
row = cur.Next()
while row <> None:
try:
i = str(row.nestsiteid)
print "Processing site: " +i #ADD SOME MESSAGES
#Select_analysis <in_features> <out_feature_class>
#{where_clause}
gp.Select_analysis(data, "tmp"+i+".shp", \
"\"nestsiteid\" = "+i+"") # REPLACED WITH DATA VARIABLE
# Viewshed_sa (in_raster, in_observer_features, out_raster,
#z_factor, curvature_correction, refractivity_coefficient)
gp.ViewShed_sa ("elev30m", "tmp"+i+".shp", \
"tmpras"+i,"" ,"" ,"" )
row = cur.Next()
except:
print gp.GetMessage()
del cur
print "Done!"
del gp
# note the line continuation \ character is used in the above code.

You might also like