ws scripting startslides
TRANSCRIPT
Getting Started with Scripting in ArcGIS 9 Transcript
Copyright © 2005 ESRI
All rights reserved.
The information contained in this document is the exclusive property of ESRI. This work is protected under United States copyright
law and other international copyright treaties and conventions. No part of this work may be reproduced or transmitted in any form or
by any means, electronic or mechanical, including photocopying and recording, or by any information storage or retrieval system,
except as expressly permitted in writing by ESRI. All requests should be sent to Attention: Contracts and Legal Services Manager,
ESRI, 380 New York Street, Redlands, CA 92373-8100, USA.
The information contained in this document is subject to change without notice.
@esri.com, 3D Analyst, ADF, AML, ARC/INFO, ArcAtlas, ArcCAD, ArcCatalog, ArcCOGO, ArcData, ArcDoc, ArcEdit, ArcEditor,
ArcEurope, ArcExplorer, ArcExpress, ArcFM, ArcGIS, ArcGlobe, ArcGrid, ArcIMS, ArcInfo Librarian, ArcInfo, ArcInfo-
Professional GIS, ArcInfo-The World's GIS, ArcLocation, ArcLogistics, ArcMap, ArcNetwork, ArcNews, ArcObjects, ArcOpen,
ArcPad, ArcPlot, ArcPress, ArcQuest, ArcReader, ArcScan, ArcScene, ArcSchool, ArcSDE, ArcSdl, ArcStorm, ArcSurvey, ArcTIN,
ArcToolbox, ArcTools, ArcUSA, ArcUser, ArcView, ArcVoyager, ArcWatch, ArcWeb, ArcWorld, Atlas GIS, AtlasWare, Avenue,
BusinessMAP, Database Integrator, DBI Kit, ESRI, ESRI-Team GIS, ESRI-The GIS Company, ESRI-The GIS People, FormEdit,
Geographic Design System, Geography Matters, Geography Network, GIS by ESRI, GIS Day, GIS for Everyone, GISData Server,
InsiteMAP, JTX, MapBeans, MapCafé, MapObjects, ModelBuilder, MOLE, NetEngine, PC ARC/INFO, PC ARCPLOT, PC
ARCSHELL, PC DATA CONVERSION, PC STARTER KIT, PC TABLES, PC ARCEDIT, PC NETWORK, PC OVERLAY, PLTS,
Rent-a-Tech, RouteMAP, SDE, SML, Spatial Database Engine, StreetEditor, StreetMap, TABLES, the ARC/INFO logo, the ArcCAD
logo, the ArcCAD WorkBench logo, the ArcCOGO logo, the ArcData logo, the ArcData Online logo, the ArcEdit logo, the
ArcExplorer logo, the ArcExpress logo, the ArcFM logo, the ArcFM Viewer logo, the ArcGIS logo, the ArcGrid logo, the ArcIMS
logo, the ArcInfo logo, the ArcLogistics Route logo, the ArcNetwork logo, the ArcPad logo, the ArcPlot logo, the ArcPress for
ArcView logo, the ArcPress logo, the ArcScan logo, the ArcScene logo, the ArcSDE CAD Client logo, the ArcSDE logo, the
ArcStorm logo, the ArcTIN logo, the ArcTools logo, the ArcView 3D Analyst logo, the ArcView Business Analyst logo, the ArcView
Data Publisher logo, the ArcView GIS logo, the ArcView Image Analysis logo, the ArcView Internet Map Server logo, the ArcView
logo, the ArcView Network Analyst logo, the ArcView Spatial Analyst logo, the ArcView StreetMap 2000 logo, the ArcView
StreetMap logo, the ArcView Tracking Analyst logo, the Atlas GIS logo, the Avenue logo, the BusinessMAP logo, the Data
Automation Kit logo, the ESRI ArcAtlas Data logo, the ESRI ArcEurope Data logo, the ESRI ArcScene Data logo, the ESRI ArcUSA
Data logo, the ESRI ArcWorld Data logo, the ESRI Digital Chart of the World Data logo, the ESRI globe logo, the ESRI Press logo,
the Geography Network logo, the MapCafé logo, the MapObjects Internet Map Server logo, the MapObjects logo, the MOLE logo,
the NetEngine logo, the PC ARC/INFO logo, the Production Line Tool Set logo, the RouteMAP IMS logo, the RouteMAP logo, the
SDE logo, The World's Leading Desktop GIS, Water Writes, www.esri.com, www.geographynetwork.com, www.gisday.com, and
Your Personal Geographic Information System are trademarks, registered trademarks, or service marks of ESRI in the United States,
the European Community, or certain other jurisdictions.
Other companies and products mentioned herein are trademarks or registered trademarks of their respective trademark owners.
Copyright © 2005 ESRI. All rights reserved. 1
Presenter: Krista Page ESRI Redlands, California
Getting Started with Scripting in ArcGIS 9
Welcome to the Getting Started with Scripting in ArcGIS 9 Live Training Seminar. My name is
Krista Page and I will be your presenter for this seminar. With me today is Jeremiah Lindemann
who will be helping to answer your questions.
Copyright © 2005 ESRI. All rights reserved. 2
Copyright © 2004 ESRI. All rights reserved.
Seminar overviewTopics
Introduction to scriptingWhat Python offersWhat ArcGIS offers
FormatTopics two and three are followed by a software demonstration, review, and Q & A session
1 of 21
In this seminar, we will cover three topics. Topic number one is a quick introduction to scripting.
In topic two, we will discuss what scripting functionality Python offers. And in topic number
three, we will discuss what scripting functionality ArcGIS offers.
Topics two and three are followed by a software demonstration, a review, and a Q & A session.
During the presentation, you can send Jeremiah and me questions. During the Q & A session, we
will do our best to answer as many questions as possible.
Copyright © 2005 ESRI. All rights reserved. 3
Copyright © 2004 ESRI. All rights reserved.
Introduction to scripting
So, let's get started with topic number one: Introduction to scripting.
Copyright © 2005 ESRI. All rights reserved. 4
Copyright © 2004 ESRI. All rights reserved.
Why write scripts?Automate work flow
Project and clip all feature classes in a geodatabaseUpdate a feature class with daily GPS readings
Run code at specific dates and timesEasily distribute code
Scripts are self-contained filesEasy to write
2 of 21
There are many reasons why people write scripts. But the number one reason that most people
write scripts is to automate a workflow. For example, maybe you have to project and clip a series
of feature classes in a geodatabase. Instead of projecting and clipping each feature class on a task
by task basis, you can throw the whole process into a script, and have the script do the tedious
work for you.
Another example might be that you have to update a feature class with daily GPS readings. Every
day you receive new GPS readings and every day you have to take those readings and manually
add them to an existing feature class. Instead of repeating this task every day, you can write a
script that will automatically update the feature class for you. With scripts, you can even set them
to run at a specific date and time.
Being able to run a script at a specific date and time is another reason that people write scripts.
Having the flexibility to run that script in the middle of the night when there is not much demand
on the server might be a huge benefit to some people.
A third reason that people write scripts is because they are very easy to distribute. Scripts are
stored in a single, self-contained file. There are no extra files to worry about.
Copyright © 2005 ESRI. All rights reserved. 5
The final reason that people write scripts is because they tend to be easy and quick to write. If you
compare a scripting language to a programming language (like Visual Basic), you will find that
scripting languages generally require fewer lines of code and have much simpler syntax.
Copyright © 2005 ESRI. All rights reserved. 6
Copyright © 2004 ESRI. All rights reserved.
Scripting languages ArcGIS 9 provides a scripting environmentMany languages are supported
Perl, VBScript, JScript, Python, and many moreESRI primarily supports Python
Installed with ArcGIS 9Samples and help documentation
3 of 21
Many legacy ESRI products offer a scripting environment. For example, ArcInfo Workstation has
AML. ArcView 3.x has Avenue. And now ArcGIS 9 provides a scripting environment as well.
Unlike previous versions of the software, ArcGIS 9 allows the user to pick from numerous
scripting languages, none of which are owned or managed by ESRI.
Some of these scripting languages include: Perl, VBScript, JScript, and Python.
Now since there are so many languages, ESRI had to choose one to primarily support. And we
chose Python. Python is installed with ArcGIS 9 and most samples and help documentation are
presented with Python code. All the code in this seminar will also use Python.
Copyright © 2005 ESRI. All rights reserved. 7
Copyright © 2004 ESRI. All rights reserved.
Scripting functionality
What Python offers What ArcGIS offers
Location to write and execute code
4 of 21
Now for anyone out there that currently uses AML, Avenue, or Visual Basic, you might be
wondering "What exactly can be done with ArcGIS 9 scripting"? And for those of you who have
never done any scripting, I am sure you are wondering the same thing. Well for the next 55
minutes we are going to focus on that question: "What can be done with ArcGIS 9 scripting?"
"What functionality is available?"
Well there is really two parts to the answer of this question. The underlying scripting language
itself offers some functionality, and this functionality will vary from language to language. And
then ArcGIS offers some functionality that is language independent. The following two topics in
this seminar are divided up based on these two parts. First we will look at what the scripting
language offers (in our case Python), and then we will look at what ArcGIS offers. So let's go
through a quick list of the functionality that we are going to cover…
The first thing that Python offers is a location to write and execute code.
Copyright © 2005 ESRI. All rights reserved. 8
Copyright © 2004 ESRI. All rights reserved.
Scripting functionality
What Python offers What ArcGIS offers
Location to write and execute code
Data types
4 of 21
The second thing that Python offers is a series of data types, including: strings, numbers, lists,
files, etc.
Copyright © 2005 ESRI. All rights reserved. 9
Copyright © 2004 ESRI. All rights reserved.
Scripting functionality
What Python offers What ArcGIS offers
Location to write and execute code
Data types
Modules and functions
4 of 21
The third thing that Python offers is a wealth of functionality tied up in modules and functions.
Copyright © 2005 ESRI. All rights reserved. 10
Copyright © 2004 ESRI. All rights reserved.
Scripting functionality
What Python offers What ArcGIS offers
Location to write and execute code
Data types
Modules and functions
Statements
4 of 21
And the fourth thing that Python offers is a series of statements. All four of these things—
location to write and execute code, data types, modules and functions, and statements—are
specific to Python. Other scripting languages, such as VBScript or JScript, do offer similar
functionality, but in a different flavor.
Copyright © 2005 ESRI. All rights reserved. 11
Copyright © 2004 ESRI. All rights reserved.
Scripting functionality
What Python offers What ArcGIS offers
Location to write and execute code
Data types
Modules and functions
Statements
Tools and environment settings
4 of 21
Now the first thing that ArcGIS offers is a set of geoprocessing tools and environment settings
that can be run, or set, from any supported scripting language.
Copyright © 2005 ESRI. All rights reserved. 12
Copyright © 2004 ESRI. All rights reserved.
Scripting functionality
What Python offers What ArcGIS offers
Location to write and execute code
Data types
Modules and functions
Statements
Tools and environment settings
Data descriptions
4 of 21
The second thing that ArcGIS offers is the ability to create data descriptions.
Copyright © 2005 ESRI. All rights reserved. 13
Copyright © 2004 ESRI. All rights reserved.
Scripting functionality
What Python offers What ArcGIS offers
Location to write and execute code
Data types
Modules and functions
Statements
Tools and environment settings
Data descriptions
Data lists
4 of 21
The third thing that ArcGIS offers is the ability to create lists of data.
Copyright © 2005 ESRI. All rights reserved. 14
Copyright © 2004 ESRI. All rights reserved.
Scripting functionality
What Python offers What ArcGIS offers
Location to write and execute code
Data types
Modules and functions
Statements
Tools and environment settings
Data descriptions
Data lists
Row manipulation
4 of 21
ArcGIS also offers the ability to manipulate rows in a table or feature class.
Copyright © 2005 ESRI. All rights reserved. 15
Copyright © 2004 ESRI. All rights reserved.
Scripting functionality
What Python offers What ArcGIS offers
Location to write and execute code
Data types
Modules and functions
Statements
Tools and environment settings
Data descriptions
Data lists
Row manipulation
Geometries
4 of 21
The fifth thing that ArcGIS offers is the ability to work with geometries, for example, create new
point or line features.
Copyright © 2005 ESRI. All rights reserved. 16
Copyright © 2004 ESRI. All rights reserved.
Scripting functionality
What Python offers What ArcGIS offers
Location to write and execute code
Data types
Modules and functions
Statements
Tools and environment settings
Data descriptions
Data lists
Row manipulation
Geometries
Location to execute code
4 of 21
And the final thing that ArcGIS offers is an execution environment; an interface to run your script
from. Now all of this functionality—tools and environment settings, data descriptions, data lists,
row manipulation, geometries, and location to execute code—is available for any supported
scripting language. It is not just specific to Python.
Copyright © 2005 ESRI. All rights reserved. 17
Copyright © 2004 ESRI. All rights reserved.
Scripting functionality
What Python offers What ArcGIS offers
Location to write and execute code
Data types
Modules and functions
Statements
Tools and environment settings
Data descriptions
Data lists
Row manipulation
Geometries
Location to execute code
4 of 21
Well let's take a look at what Python can do. The next four slides correspond to these four boxes
Copyright © 2005 ESRI. All rights reserved. 18
Copyright © 2004 ESRI. All rights reserved.
What Python offers
What Python offers.
Copyright © 2005 ESRI. All rights reserved. 19
Copyright © 2004 ESRI. All rights reserved.
Location to write and execute codeThe PythonWin application
PythonWin installed with ArcGIS 9Write, test, debug, save, run code from one location
5 of 21
The first thing that Python offers is an environment where you can write and execute your code.
The application is called PythonWin, and it is installed with ArcGIS 9. In the scripting world,
PythonWin is kind of the equivalent to one stop shopping. From PythonWin, you can write, test,
debug, save, and run your code all from one location.
Copyright © 2005 ESRI. All rights reserved. 20
Copyright © 2004 ESRI. All rights reserved.
Location to write and execute codeThe PythonWin application
PythonWin installed with ArcGIS 9Write, test, debug, save, run code from one location
Write
5 of 21
You will write most of you code in what's called a script window.
Copyright © 2005 ESRI. All rights reserved. 21
Copyright © 2004 ESRI. All rights reserved.
Location to write and execute codeThe PythonWin application
PythonWin installed with ArcGIS 9Write, test, debug, save, run code from one location
Test
5 of 21
You can test individual lines of code in the Interactive Window.
Copyright © 2005 ESRI. All rights reserved. 22
Copyright © 2004 ESRI. All rights reserved.
Location to write and execute codeThe PythonWin application
PythonWin installed with ArcGIS 9Write, test, debug, save, run code from one location
Debug
5 of 21
PythonWin offers a set of debugging tools built right into the application. These tools will help
find your errors.
Copyright © 2005 ESRI. All rights reserved. 23
Copyright © 2004 ESRI. All rights reserved.
Location to write and execute codeThe PythonWin application
PythonWin installed with ArcGIS 9Write, test, debug, save, run code from one location
Save
5 of 21
You can save any of the code that you write using the Save button on the Standard toolbar.
Copyright © 2005 ESRI. All rights reserved. 24
Copyright © 2004 ESRI. All rights reserved.
Location to write and execute codeThe PythonWin application
PythonWin installed with ArcGIS 9Write, test, debug, save, run code from one location
Run
5 of 21
And you can run your code by clicking the running man icon on the Standard toolbar.
Copyright © 2005 ESRI. All rights reserved. 25
Copyright © 2004 ESRI. All rights reserved.
Data typesNumbers
num = 1.2exp = 3 + 5
Stringsfolder = "C:/Student"whereClause = "[STREET_NAM] = 'CATALINA'"
ListsfcList = ["Roads", "Streets", "Parcels"]fcList[1] ---> "Streets"
Filescoord = open("C:\\XY.txt", "r").read()
6 of 21
The second thing that Python offers is data type support. Python can store and work with many
types of data. The four most common types of built-in data types that Python supports are:
numbers, strings, lists, and files. Tuples and dictionaries are also common built-in types, but we
don't have enough time to discuss them all.
Numbers are simply numeric values. They can store integers, floating-point values, complex
numbers, and the result of an expression.
Strings are an ordered collection of characters used to store and represent text-based information.
Strings can store something as simple as a path name, or something a little more complex, like a
where clause.
Lists are a collection of ordered values that are indexed – meaning you can pull individual values
out of the list. The indexing starts at zero.
Files store the contents of a file. In Python, you can open, read, and write to files.
Copyright © 2005 ESRI. All rights reserved. 26
Copyright © 2004 ESRI. All rights reserved.
Modules and functionsModule: A file that contains functionsFunction: A task that returns a value
7 of 21
The third thing that Python offers is modules and functions. A module is simply a file that
contains functions. And a function is simply a task that returns a value. Most of Python's
functionality is locked up in dozens and dozens of modules.
Copyright © 2005 ESRI. All rights reserved. 27
Copyright © 2004 ESRI. All rights reserved.
Modules and functionsModule: A file that contains functionsFunction: A task that returns a value
The math moduleimport mathmath.sqrt(64)math.pi
The string moduleimport stringstring.split("-155.3 -43.5")string.upper("c:\\student")
The os.path moduleimport os.pathos.path.basename("C:\\Student\\Streets.shp")os.path.dirname("C:\\Student\\Streets.shp")
7 of 21
To access the functions in a module, you need to import the module. In the example on the slide,
three modules are being imported: the math module, the string module, and the os.path module.
Once the module is imported, you can access the functions in a module by prefixing the name of
the module to the name of the function. For example, to access the square root function in the
math module, type math.sqrt. This function returns a value of eight.
Some modules contain dozens of functions, and other modules contain just a few. In total there
are hundreds of functions available to any Python programmer.
Copyright © 2005 ESRI. All rights reserved. 28
Copyright © 2004 ESRI. All rights reserved.
StatementsPerform a task, but do not return a value
8 of 21
The fourth thing that Python offers (and the last thing that we will look at for Python
functionality) is statements. Statements are very similar to functions, in that they perform some
task, but they differ from a function because statements do not return a value to the user.
Copyright © 2005 ESRI. All rights reserved. 29
Copyright © 2004 ESRI. All rights reserved.
StatementsPerform a task, but do not return a value
Import a moduleimport mathimport string
Report output to the Interactive Windowprint "Hello"
Conditional statements if…elif…else
Loopswhilefor…in
Error handlingtry…except
8 of 21
Here are some examples of very common statements that you will use over and over again in
your geoprocessing scripts.
The first one is the “import” statement that we just looked at on the last slide. The import
statement imports a module.
The second one is the “print” statement. This statement is generally used to send output from a
script window to the Interactive Window (the window that we use for testing).
The third set of statements are conditional statements. Every programming or scripting language
has the ability to make decisions. Python uses the “if – elif – else” statements for decision
making.
Python also supports looping and uses the while and for statements to manage loops.
To handle and trap errors, use the “try” and “except” statements. If you throw all of your code
into a try statement, and there is an error with that code, Python will automatically skip to the
except statement. In the except statement, you, as the programmer, gets to decide how to handle
the error.
Copyright © 2005 ESRI. All rights reserved. 30
Copyright © 2004 ESRI. All rights reserved.
Scripting functionality
What Python offers What ArcGIS offers
Location to write and execute code
Data types
Modules and functions
Statements
Tools and environment settings
Data descriptions
Data lists
Row manipulation
Geometries
Location to execute code
9 of 21
Well we just looked at the four main things that Python has to offer: a location to write and
execute code, the support for many data types, dozens of modules and hundreds of functions, and
many built-in statements.
Python also offers a lot of additional functionality (like the ability to make your own classes), but
we obviously don’t have time to cover everything. What we are looking at is the basics.
Copyright © 2005 ESRI. All rights reserved. 31
Copyright © 2004 ESRI. All rights reserved.
Software Demonstration
At this point let's do a software demonstration to hammer home some of these concepts.
I’d like to move over to Python Win, which is the application that allows us to write our code,
debug our code, test our code, save our code—everything can be done from this particular
application, and this application is installed with ArcGIS 9. Down at the bottom, we see the
Interactive window. This is the location where you can test your code. We can open a brand new
Script window by going to File>New.
In the Script window is generally where you write your code, so let’s save the Script window.
Once you write some code in your Script window, you can run it by clicking this running-man
icon. If your script happens to produce an error, you can debug the script using the debugging
tools up here on the Debugger toolbar.
So, let’s write some code. The first thing I want to take a look at are those modules and functions.
And remember, to import a module, we use the “import” statement. So, let’s import the Math
module. The Math module is one of the modules we looked at back in the presentation. Now,
from the Math module, we can grab the Square-Root function. We can grab the square root of 64,
which would return a value of 8. To test this, to see the output from this, we might throw the
Copyright © 2005 ESRI. All rights reserved. 32
“print” statement in front of the math.sqrt function. The print statement will send output down to
this Interactive window. So, let’s click our Run icon, and notice, down in the Interactive window,
a value of 8 is returned.
Now, math is just one of the dozens and dozens of modules that are available for you to work
with. If we take a look in Python’s Help, there’s a Global Module Index that will take you in and
show you all of the different modules that you can work with in Python. And, there are lots of
these different modules. Math is a module that we just took a look at. If you click on the Math
module link, it will take you into that module. You can actually scroll through and see all of the
different functions that are available for that particular module. If we scroll down far enough, we
will find that Square-Root function that we just worked with.
A couple other modules that we took a look at in the presentation were the String module and the
os.path module. Those have links as well. You can just click on the String link or the os.path link,
and that will take you into their modules and show you the functions that are available for those
modules.
Okay. Well, let’s leave functions and modules for a minute and take a look at some of Python’s
functionalities—some of its other functionality. Now, let’s take a look at its Conditional
statements. So, I’m going to use the “if-elif-else” statement. I’m just going to type a little bit of
code, let’s say “X = 6”, then I’m going to say, “If X = 5, then I want to print down to the
interactive window, the value of ‘5’.” Then I’m going to say, “Else If X = 2, then what I want to
print down to the interactive window is a value of ‘2’.” “Else, If X is not equal to (==) 5, or not
equal to (==) 2, let’s print down to the Interactive window, ‘not 5 or 2’.”
So this is just some very simple code, showing you how to use Python’s Conditional statements.
In this particular example, we assign X a value of ‘6’, and then we start testing the value of X. If
X=5, we jump in and do this statement, and then the Conditional statement is over. But, if it’s not
equal to 5, we test to see if it’s equal to 2. If it is 2, then this statement is executed. If it’s not 5 or
2, then this final statement is executed. So, hopefully, if you’re following the logic, you’ll realize
that, if we run this script, that “not 5 or 2” should be printed down to the Interactive window. So,
let’s run the script, and down in the Interactive window that’s exactly what we see: “not 5 or2.”
So, again, a very simple syntax, here, or a very simple example, here, but I want to point out the
syntax. Notice at the end of each condition we use a colon. That is something that you have to do
Copyright © 2005 ESRI. All rights reserved. 33
in Python, at the end of each Condition, use that colon. And the colon is what causes the
indentation when you press Enter. Also notice that, for the Conditional statement, there’s no “End
If” statement. There’s no way to tell Python that this Conditional statement is over, and that’s
because Python uses indentation. As soon as you un-indent your code, Python knows that that
particular condition is over. Okay, so, for those of you who have worked with programming or
scripting languages before, that might be something new for you to get used to.
Well, I want to continue on, looking at Python’s looping ability, so, what I want to do is I want to
comment out all of this code—I’m just selecting it all—so that it doesn’t run again. I then right-
click, click Source Code, and click Comment Out Region. Okay, now that code will not execute.
So, let’s take a look at Python’s While loop. I’m going to assign X another value of 10, and I’m
going to say, “While X is less than 20:—notice when I press Enter, it automatically indents for
me—I’m going to print the value of X to the interactive window. I press Enter again—it’s still
indented—and then I’m going to increment the value of X by one, press Enter again. To un-
indent, I can just press Enter a second time. So, this is Python’s While loop. Again, very simple
example. We assign X a value of 10, and then we go into the While Loop. While X is less than
20, as long as X is less than 20, go into this loop and perform these actions. At this point, X is
less than 20, it’s equal to 10, so we go into the loop, print the value of X to the Interactive
window, and then increment X by one, so that it’s now equal to 11. So, when we run this loop, we
just see the value starting at ten, print it to the Interactive window, all the way up to 19. Once it
hits the value of twenty, it no longer goes into the loop. So let’s run this code.
If we come down to our interactive window, and we scroll down—we see the value of 10, all the
way down to the value of 19, and it stops at 19. Again, a very simple example, but showing you
how Python’s looping works. Again, you have to use that colon and notice there’s no End While
or End Loop statement. As soon as you un-indent, Python knows that that loop is over. Okay,
well let’s Comment Out this code—again we’ll just select it, we’ll right-click, go to Source Code
and click Comment Out Region.
The final thing I want to take a look at, here, is Python’s data types. So, we just looked at
Python’s modules and functions, and we looked at Python’s Conditional statements and loops.
Now I want to look at those data types a little bit. I mentioned there’s a number of different types
Copyright © 2005 ESRI. All rights reserved. 34
of data types—numeric would be one of them, and we see that X can store a value of 10, that is a
numeric value—but a couple other ones that I want to look at are the List and the String.
So let’s make a variable that holds a list—we’ll call it fcList, and we’ll set it equal to a series of
feature class names. So let’s say Roads, Streams, and we’ll go with Landuse. And notice that lists
are surrounded in brackets. Okay, that’s what defines a list in Python. Now lists are indexed and
they start the indexing at zero. So, for example, if I said pull value zero to the list, I’d get Roads.
If I said pull value one out, I’d get Streams, and pull value two out, I would get Land-Use. With
lists you can also grab a range. So, for example, I’m going to grab, from my list, values 0 to 2,
and I want to print that result down to the Interactive window, so I use that “print” statement.
Now, the funny thing about Python’s lists is it will start at this position—the start position—and
grab Roads, and it goes to position number 2, but it never grabs that last position. So, in this case,
we’ll get 0 to 1—it should return Roads and Streams. So let’s run this code, and that’s exactly
what we see down in the Interactive window, the values of Roads and Streams.
Now, the last data type I want to take a look at is Strings. So in a variable called FC, I’m going to
store a string called Railroads.shp, so this would represent a particular name of a shapefile. Now,
strings are also indexed, and I can pull out a series of values, and what I’d like to pull out, here, is
value 0—everything from the beginning—but I want to cut off the last four values. I actually
want to cut off the dot, the ‘s’, the ‘h’, and the ‘p’. So, now, if I run this, what I should see down
in the Interactive window is Railroads, without the .shp extension. So, I’m going to run this code,
we’ll scroll down to the bottom of our Interactive Window, and that’s exactly what we see: the
last output was Railroads.
Now, this might be useful to you, for example, if you want to convert a series of feature classes
or, sorry, a series of shapefiles into feature classes in the geodatabase, but you want to drop the
.shp extension, this might be a very easy way for you to do that. Just grab everything from the
beginning and drop the last four characters.
Okay, well that’s all I’m going to show you in the Python Win application. Now, just as a review
here, or just as a sum: Python has full support for data types, loops, conditional statements, and it
gives you access to hundreds of functions, which are stored in modules. So, let’s return to our
presentation, and let’s do a review of the topics we have covered so far.
Copyright © 2005 ESRI. All rights reserved. 35
Copyright © 2004 ESRI. All rights reserved.
Review and Q & AReasons to write scripts
Automate work flowRun code at specific dates and timesEasy to write and distribute
ArcGIS 9 scripting environmentWhat Python offers
Location to write and execute codeData typesModules and functionsStatements
10 of 21
There are four main reasons why people write scripts: to automate a workflow, to have the
flexibility of running a program at a specific date and time, to have an easy way to distribute
functionality to a user, and because they are very easy and quick to write. ArcGIS 9 provides a
scripting environment where users can choose to code in one of many different languages. ESRI
has chosen to primarily support Python. Python offers a lot of functionality, including, but not
limited to, a location to write and execute code, the support for many data types, dozens of
modules and hundreds of functions, and many built-in statements. At this point we are going to
take a few minutes to answer some of your questions. I will now turn it over to you, Jeremiah.
Okay. Thanks, Krista.
Question From Peter in Anglewood: Where can I download Python Win from?
Answer So, first, to reiterate what Krista mentioned, is that when we install ArcGIS, Python and
Python Win is included, so you don’t need to worry about going out and installing anything. You
automatically get this scripting environment to use when you install ArcGIS Desktop. Now, if
you have the case where you don’t have ArcGIS Desktop yet, and you want to start looking at
Python, and you know you’re going to be working with it in ArcGIS in the future, you can
download Python for free. So, that’s one of the advantages of using Python, is that it’s free. If you
Copyright © 2005 ESRI. All rights reserved. 36
want to download Python, there are actually two parts that you would need to have to use Python
Win. You first need Python, which gives you access to the scripting language itself, which you
can download from www.python.org. That’s a free download, and that just gives you access to
Python itself. And then you also need a separate download for Python Win, which was the
application Krista was using to write the scripts. There are also links on python.org to download
Python Win, as well.
Question From multiple users: How do you start Python Win?
Answer Well, once you have Python Win installed, it just is easy from going to the Start menu,
going to Programs, and you should see an option for Python Win.
Question From Jim in Rochester: Does Python have a debugger?
Answer Yes. One of the advantages of using the Python Win application Krista was using is that
it does have a debugger. It has its own debugging toolbar. This means that we can set up break
points, to see where our code might be having problems—step through our code, line-by-line, to
examine it more closely, see where we may have made syntax errors or how we are interacting
with our data.
Question From Cindy in Oakland: Can I run a script at any time? And, how can I do this?
Answer Well, you can do this with the Windows “at” command or using the Windows
Scheduler. This is by going into the Control Panel. And then, what you’ll do is you’ll just point to
that Python file, the py file, and you’ll tell it what time you want to run it.
Question From Cindy in Oakland: If I want to run a geoprocessing script outside of ArcMap, can
I do that as well?”
Answer Yes. We don’t even need to have ArcMap or ArcCatalog open. As a matter of fact, what
Krista’s been showing is just what we can do with Python itself. We haven’t even gotten into
ArcObjects yet—is what she’ll be getting into next—and you can run these scripts without having
ArcMap or ArcCatalog open.
Okay. I’ll turn it over to Krista now.
Okay. We’ll take two more questions, here.
Copyright © 2005 ESRI. All rights reserved. 37
Question From Robert in Austin: Is Python 2.3 okay? Or should I uninstall it and revert to
Python 2.2?
Answer Well, Robert, when you install ArcGIS 9, what gets installed by default is Python 2.1,
and that’s fine, but you can also overwrite that and install Python 2.3 on your own. Now, there
will be a few minor differences between something like Python 2.1 and 2.3. For example, in
Python 2.3, Boolean values are returned as true (t-r-u-e) and false (f-a-l-s-e), whereas, in 2.1,
they’re returned as a zero and a one. So, there are a few minor differences like that, but nothing
that should prevent you from using any of the valid versions of Python.
I’ll take one more question here.
Question From Mel, from Alabama asks, What are the most common modules to import for
GIS?
Answer There are probably four different modules that I use a lot: the os.path module is very
useful—it allows you to grab the base names and the directory names for different paths; the
String module, if you want to do any sort of string manipulation, which is very common, and
we’ll actually take a quick look at the String module in some code that’s coming up—that’s a
very useful one; the Math module, if you want to do any sort of mathematical calculations, maybe
do some mathematical calculations to add new values into a new field—that might be a useful
module for you; and the final module that we use a lot is the XYX, or the Sys module, and in that
module there are a number of things that you would work with. For example, there’s a function in
there called Exit, which is very useful. It allows you to prematurely exit a script. And the other
one that you will use a lot in there is the ARGV function, which allows you to accept dynamic
input from the user.
Copyright © 2005 ESRI. All rights reserved. 38
Copyright © 2004 ESRI. All rights reserved.
Review questionLocate the Review question link in the upper-left corner of your browser window. Click this link now.
11 of 21
And now I am going to ask you a question… Before I do, locate the review question link in the
upper-left corner of your browser window.
Copyright © 2005 ESRI. All rights reserved. 39
Copyright © 2004 ESRI. All rights reserved.
Review questionWhich of the following performs a task but does not return a value?A) A functionB) A statementC) A moduleD) A script
To submit your answer, click A, B, C, or D then click the Send button.
12 of 21
Here is the question: Which of the following "performs a task, but does not return a value"? Is it
A, a function; B, a statement; C, a module; or D, a script. To submit your answer, click A, B, C,
or D then click the Send button. We will answer this question towards the end of the seminar.
Copyright © 2005 ESRI. All rights reserved. 40
Copyright © 2004 ESRI. All rights reserved.
What ArcGIS offers
Our third and final topic focuses on what ArcGIS has to offer.
Copyright © 2005 ESRI. All rights reserved. 41
Copyright © 2004 ESRI. All rights reserved.
Scripting functionality
What Python offers What ArcGIS offers
Location to write and execute code
Data types
Modules and functions
Statements
Tools and environment settings
Data descriptions
Data lists
Row manipulation
Geometries
Location to execute code
13 of 21
The ArcGIS functionality is available regardless of the underlying scripting language that you
decide to use. ArcGIS offers: tools and environment settings, data descriptions, data lists, row
manipulation, geometries, and a location to execute your code. The next six slides correspond to
these six boxes.
Copyright © 2005 ESRI. All rights reserved. 42
Copyright © 2004 ESRI. All rights reserved.
Tools and environment settingsTools: up to 455
Union, Buffer, Project, Import from CAD, Delete, Geocode Addresses, Hillshade, Create TIN, Feature Outline Masks, Create Routes, Mean Center, Build, and much more…
Environment settings: 22Workspace, Cell Size, Output Coordinate System, Compression, Tile Size, Output Extent, and much more…
14 of 21
The first thing that ArcGIS offers is a set of geoprocessing tools and environment settings that
you can run or set from any geoprocessing script.
A tool is simply a geoprocessing operation (like a buffer, clip, projection, or data conversion).
And an environment setting is simply a common setting that is applied to all tools. For example,
maybe you want all of the outputs from your buffer and clip operations to go to one folder. If this
is the case, you can assign that folder to the workspace environment setting. All geoprocessing
tools will then honor that setting.
Copyright © 2005 ESRI. All rights reserved. 43
Copyright © 2004 ESRI. All rights reserved.
Tools and environment settingsTools: up to 455
Union, Buffer, Project, Import from CAD, Delete, Geocode Addresses, Hillshade, Create TIN, Feature Outline Masks, Create Routes, Mean Center, Build, and much more…
Environment settings: 22Workspace, Cell Size, Output Coordinate System, Compression, Tile Size, Output Extent, and much more…
import win32com.clientgp = win32com.client.Dispatch("esriGeoprocessing.GpDispatch.1")
14 of 21
The first thing you do when you start to write a script is type in these two lines of code. The first
line imports a module. This module allows you to work with ArcGIS's geoprocessing
functionality. The second line of code gives you access to the geoprocessing functionality. You
usually store that functionality in a variable called gp. From gp you can access all your tools and
environment settings.
Copyright © 2005 ESRI. All rights reserved. 44
Copyright © 2004 ESRI. All rights reserved.
Tools and environment settingsTools: up to 455
Union, Buffer, Project, Import from CAD, Delete, Geocode Addresses, Hillshade, Create TIN, Feature Outline Masks, Create Routes, Mean Center, Build, and much more…
Environment settings: 22Workspace, Cell Size, Output Coordinate System, Compression, Tile Size, Output Extent, and much more…
import win32com.clientgp = win32com.client.Dispatch("esriGeoprocessing.GpDispatch.1")gp.Workspace = "C:\\Data\\Canada.mdb"gp.Buffer("Streams", "NoBuildZone", 100)gp.Erase("LandUse", "NoBuildZone", "BuildZone")
14 of 21
After you have created the gp variable, just prefix it to any tool or environment setting. In the last
three lines of code, we are setting a workspace, buffering a feature class, and erasing features
from a feature class. The third line of code uses the workspace environment setting, and the last
two lines of code use the buffer and the erase tools. Any environment settings or tools can be
called in this fashion.
Copyright © 2005 ESRI. All rights reserved. 45
Copyright © 2004 ESRI. All rights reserved.
Data descriptionsFeature classes, geodatabases, feature datasets, coverages, folders, rasters, tables
dscFC = gp.Describe("C:\\SanDiego.mdb\\Zipcodes")if dscFC.ShapeType == "Polygon":## Calculate the area
15 of 21
The second thing that ArcGIS offers is the ability to create data descriptions. You can describe
feature classes, geodatabases, feature datasets, coverages, and many other types of data. Once you
have described a data set, you can use that description in your code.
In the example on the slide, we are describing the Zipcodes feature class and storing the
descriptive information in a variable called d-s-c-F-C. One of the descriptive pieces of
information that you can get for a feature class is its shape type. Using Python's if statement, test
to see if the Zipcodes feature class is a polygon feature class. If so, we will do some area
calculations.
Now maybe you are wondering what other descriptive pieces of information you can get for a
feature class…
Copyright © 2005 ESRI. All rights reserved. 46
Copyright © 2004 ESRI. All rights reserved.
Data descriptionsFeature classes, geodatabases, feature datasets, coverages, folders, rasters, tables
dscFC = gp.Describe("C:\\SanDiego.mdb\\Zipcodes")if dscFC.ShapeType == "Polygon":## Calculate the area
15 of 21
Well here is a list of the available properties. You can get the feature type, whether the feature
class has M or Z values, a list of fields, the extent, and many more. Each type of data you
describe will have a different set of properties. Let's look at one more example…
Copyright © 2005 ESRI. All rights reserved. 47
Copyright © 2004 ESRI. All rights reserved.
Data descriptionsFeature classes, geodatabases, feature datasets, coverages, folders, rasters, tables
dscRD = gp.Describe("C:\\Tahoe\\erelev")gp.Clip("arhill", dscRD.Extent, "erhill")
15 of 21
In this example, we are describing the e-r-e-l-e-v raster dataset. The raster dataset is represented
by the blue outline. The descriptive information is stored in the d-s-c-R-D variable. One of the
descriptive pieces of information that you can get for a raster dataset is the extent. We use that
information as input into the clip tool. We clip the green dataset (a-r-hill) to the extent of the blue
dataset (e-r-e-l-e-v) and call the output e-r-hill.
If you are wondering what other descriptive pieces of information you can get for a raster dataset,
let's have a look…
Copyright © 2005 ESRI. All rights reserved. 48
Copyright © 2004 ESRI. All rights reserved.
Data descriptionsFeature classes, geodatabases, feature datasets, coverages, folders, rasters, tables
dscRD = gp.Describe("C:\\Tahoe\\erelev")gp.Clip("arhill", dscRD.Extent, "erhill")
15 of 21
You can get the band count, the compression type, the mean cell height, the pixel type, and many
more.
Copyright © 2005 ESRI. All rights reserved. 49
Copyright © 2004 ESRI. All rights reserved.
Data listsFields, indexes, rasters, tables, workspaces, datasets, feature classes
gp.Workspace = "C:\\Tahoe"rdList = gp.ListRasters("h*")rd = rdList.Next()while rd:
gp.BuildPyramids(rd)rd = rdList.Next()
16 of 21
The third thing that ArcGIS offers is the ability to create lists of data. You can get a list of all the
fields in a table or feature class, all the rasters in a folder, all the feature classes in a folder, and
many other lists are available as well. Once you get a list of data, you can use Python's while
statement to loop through each value in the list.
In the example on the slide, we are listing all of the raster datasets in the Tahoe folder that begin
with the letter H. We then loop through the entire list, building pyramids for each raster dataset.
BuildPyramids is a geoprocessing tool.
Copyright © 2005 ESRI. All rights reserved. 50
Copyright © 2004 ESRI. All rights reserved.
Row manipulation (cursors)Read, edit, assign attribute valuesAdd and delete rows
17 of 21
The fourth thing that ArcGIS offers is row manipulation. You can read, edit, and assign attribute
values to rows. You can also add and delete rows. This functionality is referred to as cursors.
In the example on the slide, we want to replace all the occurrences of the word INTERSTATE
with INT. We want the table on the left to look like the table on the right.
Copyright © 2005 ESRI. All rights reserved. 51
Copyright © 2004 ESRI. All rights reserved.
Row manipulation (cursors)Read, edit, assign attribute valuesAdd and delete rows
gp.Workspace = "C:\\SanDiego.mdb"cur = gp.UpdateCursor("Freeways","[Fwy_Name] LIKE 'INT*'")row = cur.Next()while row:
row.Fwy_Name = string.replace(row.Fwy_Name,"INTERSTATE","INT")
cur.UpdateRow(row)row = cur.Next()
17 of 21
Here is the code to do this. Notice that we use a cursor to access the rows in the Freeways feature
class that have the letters INT. We then use Python's “while” statement to loop through each
individual row. For each row we use Python's replace function (available from the string module)
to replace all the occurrences of INTERSTATE with INT.
Copyright © 2005 ESRI. All rights reserved. 52
Copyright © 2004 ESRI. All rights reserved.
GeometriesRead, create, and edit geometries
18 of 21
The fifth thing that ArcGIS offers is the ability to read, create, and edit geometries (or, x/y
coordinates). In the example on the slide, we want to add one new feature to this coffee shops
feature class. We need to create an x/y point for the coffee shop location.
Copyright © 2005 ESRI. All rights reserved. 53
Copyright © 2004 ESRI. All rights reserved.
GeometriesRead, create, and edit geometriesgp.Workspace = "C:\\Redlands.mdb"cur = gp.InsertCursor("CoffeeShops")row = cur.NewRow()row.Name = "Starbucks"pnt = gp.CreateObject("Point")pnt.X = 481423pnt.Y = 3767370row.Shape = pntcur.InsertRow(row)del cur
18 of 21
Here is the code to do that. We use a cursor to create a new row. We then create a new point that
stores the x and y coordinates. Finally, we assign this point to the row's shape field.
Copyright © 2005 ESRI. All rights reserved. 54
Copyright © 2004 ESRI. All rights reserved.
Location to execute code
Dialog
19 of 21
The sixth thing that ArcGIS offers (and the last thing that we will look at for ArcGIS
functionality) is a location to execute your code.
You can tie your script into a tool in ArcToolbox and run that script as a dialog from ArcMap or
ArcCatalog.
Copyright © 2005 ESRI. All rights reserved. 55
Copyright © 2004 ESRI. All rights reserved.
Location to execute code
Dialog
Command line
19 of 21
You can also run a script from the Command Line environment, just like any other tool.
Copyright © 2005 ESRI. All rights reserved. 56
Copyright © 2004 ESRI. All rights reserved.
Location to execute code
Dialog
ModelCommand line
19 of 21
And finally, you can add your script to a model and run the script from there. You can take the
output from your script tool and make it input into another tool.
So that was the last thing that we are going to look at for ArcGIS functionality.
Copyright © 2005 ESRI. All rights reserved. 57
Copyright © 2004 ESRI. All rights reserved.
Review question resultsTo view the results, click the Review question link in the upper-left corner of your browser window.
Which of the following performs a task but does not return a value?
A) A functionB) A statementC) A moduleD) A script
20 of 21
Before we do the software demonstration, let's see how many of you got the correct answer to the
review question. For "which of the following performs a task but does not return a value", the
correct answer is…
Copyright © 2005 ESRI. All rights reserved. 58
Copyright © 2004 ESRI. All rights reserved.
Review question resultsTo view the results, click the Review question link in the upper-left corner of your browser window.
Which of the following performs a task but does not return a value?
A) A functionB) A statementC) A moduleD) A script
20 of 21
B) A statement.
Copyright © 2005 ESRI. All rights reserved. 59
Copyright © 2004 ESRI. All rights reserved.
Software Demonstration
At this point, let’s do a software demonstration that will focus on different scripts that can be
created using the ArcGIS scripting functionality. So, at this point I’d like to move over to
ArcMap.
In this ArcMap session, I have a map document open called sandiego.mxd. Within this map
document I have three different feature classes open: the Oceans feature class, the Zipcodes
feature class, and the Hotels feature class. Also notice that I have a toolbox called Custom
Tools—a toolbox that I created—that stores five different scripts. The ‘S’ symbol represents a
script symbol. Behind each one of these tools is a Python script, and we’ve taken that Python
script and we’ve attached it to a tool in ArcToolbox. As soon as you do that, it becomes part of
what’s called the geoprocessing framework, and you can now run this script from many different
locations. For example, I can double-click on a script and it opens up a dialog and I can run this
script from this location. It puts a nice front-end user interface on this particular script.
Something else that I can actually do is I can open what’s called the Command Line window, and
in the Command Line window I can type in the name of that script. Notice when I type in
Convert, that particular script pops up. So, again, as soon as you add it to a tool in ArcToolbox, it
Copyright © 2005 ESRI. All rights reserved. 60
behaves like any other tool and I can run it from this particular environment. Also, notice that the
usage pops up as well, telling me exactly what I need to input.
The other place that you can run this script is from a model. So, if I add a new model, or an empty
model, to my Custom Tools toolbox, I can take any one of these scripts and drag them into the
model and run them from a model. I could take the output from this convert XY to point script,
and I could attach this output to maybe another geoprocessing tool and run these tools in
succession.
So, what I’d like to do at this point is go through these different scripts and show you how some
of the functionality was created, or how some of the scripts were written. The first script I want to
look at is this Delete Files script. If I double-click on this script, there’s a description over here
that tells me that this script deletes a set of files from a folder. Okay, notice I have a default folder
in here called D:\DemoData\JunkFolder. Also notice there’s a drop-down list where you can
choose which kind of files you want to delete. Notice that mxd is one of those types.
So, let’s go over to ArcCatalog and see what we have in that JunkFolder. Okay, so in JunkFolder
I have a series of map documents, and I want to delete those map documents, but I don’t want to
have to open ArcCatalog to do that. I just want to be able to run this script from ArcMap and
clean up data when necessary. So, let’s go back over to that Delete Files script, double-click it,
specify that we want to delete mxd files, and click Okay. When the script has finished running, hit
Close on the progress dialog, go back over to ArcCatalog, right-click on JunkFolder and do a
Refresh, and notice that all those map documents are gone. Pretty simple script, but it performs
some very useful functionality.
Now let’s right-click this script tool—you can right-click any script tool, and you can click Edit—
and what it actually does, is it pops up that script tool inside of Python Win, and you can see
everything behind that tool was just some Python code. Now, the majority of this is just
comments, and if we look at the actual code that performed that—here it is, right here—not a lot
of code, maybe six or seven lines of code to perform something fairly useful. Notice, in here,
we’re not really using any ArcGIS functionality, we’re using straight Python functionality. So, we
import two different modules, SYS and OS. We use the SYS to grab dynamic input from the user,
using that ARGV function. Also notice, from the OS module, that we’re using some of its
Copyright © 2005 ESRI. All rights reserved. 61
functions: we’re listing the directories in a particular folder, and then we’re also removing them,
or deleting them.
Well, let’s take a look at our next script, called Shapefile Information. Now, what this script does
is it reports the name, shape type, and number of fields for each shapefile in a folder. Okay, so a
fairly simple script. It’s just going to report some shapefile information right to a progress dialog.
So, I’m going to click Okay. I’ve got a folder selected. Notice I can put default values in here. I
can also browse to my own location. But, I’m going to click Okay, and in this progress dialog, it’s
going to go through and it’s going to list the information for all the shapefiles that it found in that
folder. Notice that it found a shapefile called Cities—it’s reporting that it’s a point shapefile and
that it has eight fields. Okay, then it reports the next shapefile, and so on and so forth, until it’s
reported every shapefile in that folder. Okay, and again, this is just being sent to the progress
dialog, but we could also send this to a text file, or some other location.
Well, let’s take a quick look at that script. Again, if we right-click and we go to Edit, this script
opens in Python Win. You can just see that there is some Python code in here. And what the
Shapefile information script makes use of is those data descriptions that we talked about in the
presentation. Notice that we call a Describe on a particular shapefile, and then we can get some
fields information, we can describe the fields. Somewhere we must also be describing the shape
type, because we get that back, as well; the point, line, or polygon. And, again, just making use of
those describe objects.
Okay, well the next script that I want to take a look at is called Report Geodatabase Contents.
Now, what this script does is it reports the names of all the feature datasets, feature classes,
tables, and rasters in a geodatabase to a text file. Okay, so that might be kind of handy—it’s
something that’s been handy for me—is I pick a particular geodatabase and I report the contents
of it to a text file. So, let’s run this script. And it’ll take a second to run. When it’s finished
executing, I can click the Close button, and we can go into ArcCatalog and take a look at that text
file. Now I’ll just refresh my JunkFolder, and notice a new file called GDBReport has been
added, and it gives us some information on what’s stored inside that geodatabase. There’s one
feature dataset called Census; within there, there’s a series of feature classes. Notice there are also
some stand-alone feature classes, and there’s a table, as well. Okay. So a fairly handy tool if
you’re looking for a quick report on what’s in your geodatabase.
Copyright © 2005 ESRI. All rights reserved. 62
Let’s go back to ArcMap and we’ll right-click on that tool, and we’ll click Edit, and take a quick
look at it in Python Win. Now, what this makes use of—what this particular script makes use
of—is those data lists. Remember, we can list a lot of different types of data. The first thing we
list is the feature datasets, and then, within each feature dataset, we make a list of the feature
classes. We then scroll down and we make a list of stand-alone feature classes. We make a list of
tables and a list of rasters. Okay, and all of this is being written—every single time—out to a
particular text file. So, again, we’re making use of those data lists.
Okay. Well, let’s look at our next script: Point Count. Now, what this particular script does is it
calculates the number of points in a polygon and stores a count in a field in the polygon feature
class. This tool assumes the field already exists. Now, let me explain to you what this does. Here
we have a polygon feature class called ZIPcodes, and we also have a point feature class called
Hotels. So, we want to figure out how many hotels are within each ZIP Code and store that in a
field in the ZIPcodes feature class. If I open the ZIPcodes feature class, this tool does assume that
there’s already a field that we can use to store this information. We currently have a field called
Hotel Count that we can use. If you didn’t have a field, you could just add it, and there’s also a
geoprocessing tool called Add Field that would allow you to do this right inside of the script. But
let’s go ahead and run that particular script tool. The polygon feature class is ZIP Codes, the point
feature class is Hotels, and the field that stores the count is called Hotel Count. Okay. Notice how
these are all available directly from drop-down lists. Click OK. It’s going to run through and
count each of those hotels in each ZIP Code and store that information in the field. If we open the
ZIPcodes feature class, we scroll over to the end, here, and let’s do a sort descending—we’ll see
that ZIP Code number 92101 has the largest number of hotels: 18, and that makes sense. If
you’ve ever been to the city of San Diego, which is in Southern California, you’ll know that this
is the downtown core area of San Diego.
If we right-click that script tool and go to Edit—open that in Python. What this script makes use
of is row manipulation. Using those particular cursors, we go through and we add the new value
to each one of those rows in that field. The last script that I want to look at is called Convert XY
to Point. Now, what this script does is it converts a text file with x and y coordinates to a point
feature class. So, maybe you have some text files storing some GPS readings and you want to
convert those to a feature class, and you want this to be automated. This particular tool can do
that. So, we’re going to send, or we’re going to use the Attractions text file—it has some GPS
Copyright © 2005 ESRI. All rights reserved. 63
readings in there—and we’re going to convert it to a feature class called Attractions in the San
Diego geodatabase. So let’s run this tool.
Now we can add that Attractions feature class—here it is, right here, just created for us—and
we’ll give it a little bit of symbolization so you guys can see it. And now all of these new point
features have been added to the attractions feature class, based on GPS readings in a text file.
These include things like, maybe museums and parks in the city of San Diego.
Well, let’s take a quick look at the code behind this script. Now, what this script is kind of
showing off is the ability to work with geometry. If we scroll down through the script, you’ll see
that we have to make a new point feature. And then, in that point feature, we assign different X
and Y values, creating brand new points to store in that Attractions feature class.
Now, the last thing that I want to mention is maybe you’re wondering how can I look at some
existing scripts, and a great way to do that is to look at some of the scripts that are actually
shipped with the software. So, for example, in the Conversion Tools toolbox, there’s a number of
tools that are actually built on scripts—any of these ones with the little ‘S’ icon. So, you can
right-click any of these and click Edit, and that code will actually open in Python Win and you
can view it, and see how ESRI creates their scripts, and maybe borrow some of that code to write
one of your own scripts, etc. There are a number of different tools that come with the software
that are actually stored as Python scripts.
Copyright © 2005 ESRI. All rights reserved. 64
Copyright © 2004 ESRI. All rights reserved.
Review and Q & AWhat ArcGIS offers
Tools and environment settingsData descriptionsData listsRow manipulationGeometriesLocation to execute code
21 of 21
Let's do a review of the last topic that we just covered. ArcGIS offers a lot of scripting
functionality: tools and environment settings, data descriptions, data lists, row manipulation,
geometries, and a location to execute your code. ArcGIS also offers a lot of additional
functionality (for example, error checking, error handling, and messaging). We just don't have
time to cover it all.
At this point we are going to take a few minutes to answer some of your questions. Back to you,
Jeremiah.
Thanks Krista.
Question From multiple users: Does the number of ArcGIS functionalities available to me
depend on whether I have ArcView, ArcEditor or ArcInfo?
Answer Yes, it does depend on which license level you have. The second part of this lecture,
Krista’s largely talked about what we can do from ArcGIS within Python. One of the major
things that we’re going to be doing is running geoprocessing tools, or tools that are inside
ArcToolbox. Now, those tools that you get inside ArcToolbox differ, depending on whether you
Copyright © 2005 ESRI. All rights reserved. 65
have ArcView, ArcEditor, or ArcInfo. If you have the full ArcInfo seat and all extensions, you
get nearly five hundred tools. But, you get quite a few tools, even with the ArcView seat. You get
about a hundred tools. So, it just depends on which seat you have and you need to be aware of
which tools you have available to you, whether or not you can use them within a Python script.
Question From Elizabeth in Milton: Is it possible to first create a model, then export it to a
script?
Answer Yes, you can do that. So, if you’re familiar with using the geoprocessing framework, we
can also create models and chain together tools—execute one tool after another. We take our
models and then we can export them to either a Python J Script or VB Script. So, this is a great
way to establish a workflow—a general workflow: which tools you want to execute—and then
we can put in our logic into our script, set up the branching or the looping after we have the
general flow in place.
Question From Michael in Salem: What is the best way to get help and find parameters for the
geoprocessing tools?
Answer Well, probably the best way to find out what parameters and what syntax you need for a
specific tool—for instance, if I want to run the clip tool in Python—would be to go into
ArcToolbox, right-click the tool, and choose Help. You’re going to get a lot of information about
how to use a tool, what the tool’s intended purpose was, and at the very bottom of the page, each
tool within ArcToolbox will have a script example. All these examples are within Python. So, that
will tell you what parameters are needed, and you can still see the general syntax for how to get
that tool to be used within Python.
In just a moment, Krista’s going to get back to a little bit more about other resources where we
can find out more information—more help for running our geoprocessing scripts.
Question From Oliver in Cambridge: Can I describe shapefiles?
Answer Yes, we can. Krista had a couple slides in there where she was describing raster datasets
and, in the demo, she ran a method that was called List Feature Classes. Now, a shapefile is just
another type of feature class, so you can also describe shapefiles and get information about them:
what is the type? Is it a point, line, or polygon? What are its extents? If you want more
information about which type of objects you can describe, again, go into the ArcGIS Desktop
Help. It gives you information on geoprocessing and what you can do. And there’s also a PDF
called The Geoprocessor.pdf. This will give you information on everything that you can do within
Copyright © 2005 ESRI. All rights reserved. 66
scripting. It has it all nicely diagramed-out, so you can see the workflow—what one object will
lead to another.
Question From multiple users: Does Python supply auto-completion? So, when I type in a
variable and hit a doc, can I see what methods or what tools I can use?
Answer Now Python Win does not support a true auto-completion when using the geoprocessing
tools. The reason is because the geoprocessing environment is dynamic. Meaning that, if you’re
going to be using the geoprocessor to run tools, you can have a wide variety of tools inside of
ArcToolbox depending on which license you have, and you might also put custom tools inside
ArcToolbox. For instance, you can run a model from a script. So, right up front, Python doesn’t
know which tools you have inside ArcToolbox, so it’s not aware of which tools it should be able
to run. However, you will see some completion, for instance, if I run the Add Field tool within
Python, and then I want to use it again later on, it will recognize I use it within the script, so then
I will see some auto-completion.
Question From multiple users: Why would you use Python versus using ArcObjects and VBA?
Answer Well, you can stick with ArcObjects and VBA—it can be used to do just about anything
that you want within ArcMap and ArcCatalog. Python offers a much simpler environment. You
don’t have to get into ArcObjects as much; you don’t have to write as much code. So, in general,
you can write less code to accomplish some general workflows. Now, using geoprocessing
functionality within Python, you can think of it as basically doing everything that you can do
within ArcToolbox. So, if you have general workflows you want to establish with tools from
ArcToolbox, you can use Python to quickly put together a script that will accomplish those
workflows. Now, within ArcObjects and VBA that’s where you get a little bit more robust
environment. You want to create a tool where you can interact with the display and select things
and interactively work with the ArcMap environment, then you’d probably still want to work
with VBA and ArcObjects, but Python offers you a much more flexible environment to quickly
get a script up and running.
Okay. I’ll turn it back over to Krista.
Okay. We have time for maybe just a couple more, here.
Copyright © 2005 ESRI. All rights reserved. 67
Question From someone in Lancaster: If you want to share scripts with other users, do you
distribute the entire mxd, mxt, or just the scripts?
Answer Well, this is how it works. You can just send the script to someone, you can send them
the py file, and they can open that in Python Win and run it directly from Python Win. Or, the
other option you can do is, you probably noticed in my demonstration, I had a series of those
scripts attached to tools inside of a toolbox. So, what you could actually do is distribute the
toolbox, which is a tbx file. In that case, those scripts are already attached to the toolbox. Now, if
you do that, you have to send the py files, as well.
Question From Terrell in Lawrence: We converted some models to Python scripts. They ran
successfully one time then, on repeated trials, we had errors. What might be missing?
Answer Well, a lot of people who start off with Python, they’ll run a script the first time, and it
works great. And then they go to run it a second time, and it gives them errors. And I guarantee
that the problem is probably that you ran it the first time and the output data already exists, and
now you’re trying to run it the second time, and Python gives you an error because the data was
created in the first run of the script. So, what you can actually do—there’s a property called
Overwrite Output—and you can say GP.overwriteoutput is equal to one, you can throw that at the
top of your script, and that should solve your problem.
Okay. Well, I think we’re out of time, so let’s just finish off, here.
Copyright © 2005 ESRI. All rights reserved. 68
Copyright © 2004 ESRI. All rights reserved.
For more informationInstructor – led training
Introduction to Geoprocessing Scripts using Python
Virtual Campus training Geoprocessing with ArcGIS 9
DocumentationWriting Geoprocessing Scripts.pdf
ESRI Support Center(http://support.esri.com/geoprocessing) Python home page (www.python.org)
Hopefully after this session you have a better understanding of what can be done with scripting at
ArcGIS 9. To learn more about how to script, you can take the two-day, instructor-led class called
Introduction to Geoprocessing Scripts Using Python. To learn more about geoprocessing in
general, you can take the Virtual Campus course, Geoprocessing with ArcGIS 9. There’s also a
lot of documentation to help you get started with ArcGIS 9 scripting; see the Writing
Geoprocessing Scripts PDF in the ESRI Library folder; visit ESRI support page; or visit Python’s
Web page. From Python’s Web page you can download the software, enter discussion forums,
and go through some tutorials.
Copyright © 2005 ESRI. All rights reserved. 69
Thanks for participating
On behalf of myself, Jeremiah, and the Virtual campus team, we would like to thank you for
participating in this seminar.
Copyright © 2005 ESRI. All rights reserved. 70