Introduction To Geoprocessing Scripts Using Python
Introduction To Geoprocessing Scripts Using Python
Using Python®
Student Edition
Student: Juan Salcedo Carbajal
INGEMMET
24 25 y 26 de julio 2017
Copyright © 2013 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.
EXPORT NOTICE: Use of these Materials is subject to U.S. export control laws and regulations including the U.S. Department
of Commerce Export Administration Regulations (EAR). Diversion of these Materials contrary to U.S. law is prohibited.
@esri.com, 3D Analyst, ACORN, Address Coder, ADF, AML, ArcAtlas, ArcCAD, ArcCatalog, ArcCOGO, ArcData, ArcDoc,
ArcEdit, ArcEditor, ArcEurope, ArcExplorer, ArcExpress, ArcGIS, ArcGlobe, ArcGrid, ArcIMS, ARC/INFO, ArcInfo, ArcInfo
Librarian, ArcLessons, ArcLocation, ArcLogistics, ArcMap, ArcNetwork, ArcNews, ArcObjects, ArcOpen, ArcPad, ArcPlot,
ArcPress, ArcPy, ArcReader, ArcScan, ArcScene, ArcSchool, ArcScripts, ArcSDE, ArcSdl, ArcSketch, ArcStorm, ArcSurvey,
ArcTIN, ArcToolbox, ArcTools, ArcUSA, ArcUser, ArcView, ArcVoyager, ArcWatch, ArcWeb, ArcWorld, ArcXML, Atlas GIS,
AtlasWare, Avenue, BAO, Business Analyst, Business Analyst Online, BusinessMAP, CityEngine, CommunityInfo, Database
Integrator, DBI Kit, EDN, Esri, Esri—Team GIS, Esri—The GIS Company, Esri—The GIS People, Esri—The GIS Software
Leader, FormEdit, GeoCollector, Geographic Design System, Geography Matters, Geography Network, GIS by Esri, GIS Day,
GIS for Everyone, GISData Server, JTX, MapIt, Maplex, MapObjects, MapStudio, ModelBuilder, MOLE, MPS—Atlas, PLTS,
Rent-a-Tech, SDE, SML, Sourcebook·America, SpatiaLABS, Spatial Database Engine, StreetMap, Tapestry, the ARC/INFO
logo, the ArcGIS logo, the ArcGIS Explorer logo, the ArcPad logo, the Esri globe logo, the Esri Press logo, the GIS Day logo,
the MapIt logo, The Geographic Advantage, The Geographic Approach, The World's Leading Desktop GIS, Water Writes,
www.arcgis.com, www.esri.com, www.geographynetwork.com, www.gis.com, www.gisday.com, and Your Personal
Geographic Information System are trademarks, service marks, or registered marks in the United States, the European
Community, or certain other jurisdictions. CityEngine is a registered trademark of Procedural AG and is distributed under
license by Esri.
Other companies and products or services mentioned herein may be trademarks, service marks or registered marks of their
respective mark owners.
Course introduction
Introduction ............................................................................................................................................i
Course goals ...........................................................................................................................................i
Additional resources ...............................................................................................................................i
Installing the course data ......................................................................................................................ii
2 Describing data
Lesson introduction ............................................................................................................................ 2-1
The Describe function ........................................................................................................................ 2-2
Generic Describe object properties ................................................................................................... 2-3
Feature class Describe properties ...................................................................................................... 2-4
Raster Describe properties ................................................................................................................. 2-7
Describing a feature class and raster.................................................................................................. 2-9
Fill-in-the-blank................................................................................................................................. 2-10
Exercise 2: Work with the Describe object....................................................................................... 2-13
Describe a feature class and a geodatabase ............................................................................. 2-14
Describe a list of feature classes ................................................................................................ 2-16
Clip raster datasets with Describe object properties................................................................. 2-18
Challenge: Describe dataset and coordinate system properties............................................... 2-22
Lesson review ................................................................................................................................... 2-23
i
Working with List functions ................................................................................................................ 3-6
List data .............................................................................................................................................. 3-7
Exercise 3: Automate scripts with the ArcPy List functions ................................................................ 3-9
List field properties .................................................................................................................... 3-11
Buffer feature classes ................................................................................................................. 3-13
Verify script results ..................................................................................................................... 3-16
Lesson review ................................................................................................................................... 3-17
ii
6 Working with Geometry objects
Lesson introduction ............................................................................................................................ 6-1
Creating geometry objects................................................................................................................. 6-2
Creating Point objects........................................................................................................................ 6-3
Creating Polyline geometry objects ................................................................................................... 6-6
Creating Polygon geometry objects .................................................................................................. 6-8
The geometry object........................................................................................................................ 6-10
Constructing multipart geometry ..................................................................................................... 6-12
Constructing multipart polygons...................................................................................................... 6-13
Creating and updating feature geometry ........................................................................................ 6-14
Using geometry object with geoprocessing tool ............................................................................. 6-15
Accessing geometry objects ............................................................................................................ 6-16
Exercise 6: Work with geometry objects and cursors....................................................................... 6-17
Create geometry objects ........................................................................................................... 6-18
Access Shape geometry ............................................................................................................ 6-20
Update existing features ............................................................................................................ 6-21
(Optional) Create new features .................................................................................................. 6-23
(Optional) Use geometry object with geoprocessing tool......................................................... 6-25
Lesson review ................................................................................................................................... 6-27
7 Sharing scripts
Lesson introduction ............................................................................................................................ 7-1
Terms commonly used when sharing scripts ...................................................................................... 7-2
Scripting advantages in ArcMap ........................................................................................................ 7-3
Making scripts dynamic ...................................................................................................................... 7-4
Creating and sharing a script tool ...................................................................................................... 7-6
Advantages of attaching a script to a custom tool............................................................................. 7-7
Using the Add Script wizard ............................................................................................................... 7-8
Running a script................................................................................................................................ 7-11
Sharing a script................................................................................................................................. 7-13
Plan out a project ............................................................................................................................. 7-17
Exercise 7: Share scripts through geoprocessing packages............................................................. 7-21
Add pseudocode to the script................................................................................................... 7-22
Write script code........................................................................................................................ 7-22
Attach script to custom tool....................................................................................................... 7-23
Run script in ArcMap.................................................................................................................. 7-25
Share results as a geoprocessing package ................................................................................ 7-26
Verify the geoprocessing package............................................................................................. 7-28
Lesson review ................................................................................................................................... 7-32
iii
8 Debugging scripts and handling runtime errors
Lesson introduction ............................................................................................................................ 8-1
Debugging workflow.......................................................................................................................... 8-2
Debugging scripts in PyScripter ......................................................................................................... 8-3
Handling script exceptions................................................................................................................. 8-6
Getting geoprocessing messages ...................................................................................................... 8-7
Working with exceptions .................................................................................................................. 8-10
Using Exception as e ........................................................................................................................ 8-10
Using arcpy.ExecuteError ................................................................................................................. 8-11
Using the traceback module ............................................................................................................ 8-12
Tips and best practices..................................................................................................................... 8-13
Exercise 8: Debug scripts and handle exceptions............................................................................ 8-15
Debug the script ........................................................................................................................ 8-16
Incorporate a try-except statement block.................................................................................. 8-17
Incorporate an Exception as e statement .................................................................................. 8-18
Incorporate an arcpy.ExecuteError exception class ................................................................... 8-21
Use the traceback module ......................................................................................................... 8-22
Challenge: Challenge ................................................................................................................ 8-24
Lesson review ................................................................................................................................... 8-25
Appendixes
Appendix A: Esri data license agreement ..........................................................................................A-1
iv
Appendix B: Answers to lesson review questions
Lesson 1: Running scripts in Python............................................................................................. B-1
Lesson 2: Describing data............................................................................................................ B-2
Lesson 3: Automating scripts with lists ........................................................................................ B-3
Lesson 4: Working with Selections............................................................................................... B-4
Lesson 5: Working with Cursors................................................................................................... B-5
Lesson 6: Working with Geometry objects .................................................................................. B-6
Lesson 7: Sharing scripts.............................................................................................................. B-7
Lesson 8: Debugging scripts and handling runtime errors .......................................................... B-8
Lesson 9: Automating map production ....................................................................................... B-9
v
Introduction
This course uses Python's language syntax and modules to access and
automate geoprocessing workflows through Python scripts. These
scripts can be run inside of the Python Integrated Development
Environment, within the Python window in ArcGIS Desktop, as custom
tools within ArcToolbox, or shared as geoprocessing packages.
This course covers the ArcPy site package, which integrates Python
scripts into ArcGIS Desktop and ArcGIS Server. With ArcPy, you
scripts can access additional ArcGIS functionality to work with your
maps and data beyond the geoprocessing framework.
Course goals
By the end of this course, you will be able to:
• Work with the ArcPy site package in ArcGIS for Desktop and
PyScripter for Python.
• Incorporate cursors, use the Describe function, and use Python
lists in scripts.
• Automate map document layer and layout management using
ArcPy.
• Create script tools and geoprocessing packages.
• Access resources for debugging Python code.
• Understand commonly used ArcPy classes and functions.
• Change table and feature schema for migrating data to new
feature classes and tables.
• Create geometry objects for creating and updating features and
for input to geoprocessing tools.
Additional resources
ArcGIS Resources - http://resources.arcgis.com
This site provides unified access to web-based help, online content,
and technical support.
Esri GIS Dictionary - www.esri.com/gisdictionary
This dictionary includes definitions for GIS terms related to geodata,
analysis, GIS modeling and web-based GIS, cartography, and Esri
software.
i
Installing the course data
Some exercises in this workbook require data. Depending on the
course format, the data is available on a DVD in the back of a printed
workbook or as a data download. To install the data, place the DVD in
your disc drive or double-click the data download and follow the
instructions in the installation wizard. The data will automatically be
installed in the C:\Student folder.
ii
Icons used in this workbook
Notes point out additional information, exceptions, or special
circumstances that apply to a particular topic or procedure.
iii
Running scripts in Python
1
Running scripts in Python
Introduction
Key terms In this lesson, you will explore working with the ArcPy site package
and Python to access Python and geoprocessing functionality,
IDE
automate your workflow processes, and access and update data. You
Python window will also learn how to run your scripts in ArcMap.
site package
Topics covered
Learning objectives
1-1
LESSON 1
1-2
Running scripts in Python
Figure 1.1
Workflow for running
scripts in the Python
window.
1-3
LESSON 1
1-4
Running scripts in Python
Figure 1.2
The PyScripter IDE
1-5
LESSON 1
c From the File menu, click Open, and then navigate to the C:\Student\PYTH\Running_scripts
folder.
d Click the Lesson1Activity.py script to select it, and then click Open.
f Browse through the tabs in the dialog box, and note the settings in the Display tab:
• Editor Font: You can change the size of the font used in the Editor Window here.
• Gutter: By default, line numbers are not displayed in the Editor Window gutter. Check
the Show line numbers option to enable the display of line numbers.
Notice that the script is using the ArcPy module to access geoprocessing functionality. You can
import the ArcPy module into the PyScripter Interpreter window to access code complete
functionality without having to load a script. You will learn more about ArcPy in this lesson.
c On the Debug Toolbar, click the Run button to run your script.
You could also press Ctrl+F9 on your keyboard to run the script.
1-6
Running scripts in Python
After a few moments, you receive a message in the Python Interpreter window notifying you that
the script has completed.
______________________________________________________________________________
e You may choose to run the script again, or, if you are done exploring PyScripter, you may
close the application.
Script workflow:
• Imported the ArcPy module and os modules.
• Set the current workspace environment.
• Created a list of feature classes and printed the names.
• Using the same list, ran the GetCount geoprocessing tool for each item.
• Printed the feature class name and the feature count.
• Using a data access cursor, printed the attribute values for each School feature.
Using the ArcPy module and lists of items created by the ArcPy List functions, the script
automated a geoprocessing workflow task. Using a list of items, it was easy to automate the
process of running the same geoprocessing tool on each item. The script also accessed and
displayed data values for a field. The ArcPy data access cursors provided functionality to access
and display the data values.
In upcoming lessons, you will learn tools and techniques for fixing syntax errors, debugging your
script, and catching errors that occur when the script is run in PyScripter. You will also explore how
to create lists and access data values in fields.
1-7
LESSON 1
Figure 1.3
Python 2.7 site packages
1-8
Running scripts in Python
Figure 1.4
ArcPy base functions and
classes.
1-9
LESSON 1
ArcPy functions
ArcPy functions support many geoprocessing workflows. For example,
with ArcPy functions, you can:
ArcPy classes
1-10
Running scripts in Python
Figure 1.5
ArcPy module import
syntax example.
*Nesting several functions and classes together to perform an operation with the arcpy.sa
module are explained in detail on the following page.
1-11
LESSON 1
Figure 1.6
Importing the arcpy.sa
module into a script.
import arcpy
from arcpy.sa import *
ArcGIS Help Library: arcpy.CheckOutExtension("spatial")
Importing ArcPy arcpy.env.workspace = "C:/MyData/MyProject.gdb"
ras1 = "Slope"("elevation", "DEGREE", 0.3043)
ras2 = "SolarRad"
outRAS = (Raster(ras1) + (Raster(ras2)))
pythonaddins module
This module contains functionality to support and work with the new
Python add-ins. It cannot be used in stand-alone scripts or
ArcGIS Help Library:
geoprocessing script tools. Python add-ins will not be covered in this
Essential Python add-in
course.
concepts
1-12
Running scripts in Python
1-13
LESSON 1
1-14
Running scripts in Python
Figure 1.7
Python window being
used in ArcMap to create
a buffer in an area of
Corvallis.
1-15
LESSON 1
Your task is to run the Buffer geoprocessing tool on the Corvallis schools. You will test the
geoprocessing workflow in the Python window, verify the results, and then create a Python script.
b In the Catalog window, expand the C:\Student\PYTH\Running_scripts folder, and then drag
Corvallis.mxd into the map.
c Open the Python window and move it to the bottom of the ArcMap display.
Hint: From the Standard toolbar, click the Python window button . Or, from the
Geoprocessing menu, select Python.
The Search window displays the Analysis toolbox, the Buffer tools, and other matching items.
f In the Python window, set the current workspace environment setting to the Corvallis
geodatabase:
Type arcpy.env.workspace = r'C:\Student\PYTH\Running_scripts\Corvallis.gdb',
and then press Enter on your keyboard.
g From the Search window, drag the Buffer(Analysis) tool into the Python window.
Notice that code complete displays a list of the layers from the table of contents for you to
choose from.
1-16
Running scripts in Python
j Type "BuffSchools1000", (make sure to include the comma so that you can move to the
third parameter).
k For the buffer_distance_or_field parameter value, type "1000 feet", and then enter a
closing parenthesis.
l Click just inside the closing parenthesis to view the tool syntax.
When executed, the Buffer tool will return a result that will be added to the table of contents.
m In the Python window, click outside the closing parenthesis, and then press the Enter key on
your keyboard.
o If the results are not valid: return to the Python window, recall the last command (by pressing
Up arrow on the keyboard), change the incorrect parameters, and then rerun the tool.
You are now ready to export the Python window commands to a Python script.
1-17
LESSON 1
s Click Save.
When a script is run in PyScripter, it runs outside of the ArcGIS environment. Because of this, you
will need to import the ArcPy module into the script.
c Add code at the top of the script to import the ArcPy module:
Type import arcpy.
When debugging and testing your script in a Python IDE, you may need to run the script several
times. The overwriteOutput environment setting allows the outputs of geoprocessing tools to
be overwritten without causing errors. It controls whether tools will automatically overwrite any
existing output when run. When set to True, tools will execute and will overwrite the output
dataset. When set to False, existing outputs will not be overwritten, and the tool will return an
error.
d In your script, add a new blank line just above the Buffer line of code.
1-18
Running scripts in Python
h Verify that your script matches the script in the following graphic.
i To run the script, on the Debug Toolbar, click the Run button .
The script should complete successfully and print the message "Script completed" to the Python
Interpreter window.
j Comment out the line of code in your script that sets the overwriteOutput setting to True.
Commenting out this line of code and reopening PyScripter will return the script to a default
behavior in which attempting to overwrite existing outputs with geoprocessing tools will generate
a system error, or exception. In a later lesson, you will learn how to write code to catch and handle
errors, so the an exception is not generated when the script is executed.
The final step in the workflow is to verify the script results in the ArcMap application.
l Close PyScripter.
a Open ArcMap, and then open the Corvallis.mxd from the C:\Student\PYTH\Running_scripts
folder.
1-19
LESSON 1
c In the table of contents, move the BuffSchools1000 layer so that it displays below the Building
layer.
d Verify that the buffer polygons match the buffer polygons in the following graphic.
e Close ArcMap.
1-20
Running scripts in Python
Lesson review
______________________________________________________________________________
______________________________________________________________________________
2. What is ArcPy?
______________________________________________________________________________
______________________________________________________________________________
______________________________________________________________________________
3. In the Python window, how can you view help for a geoprocessing tool?
______________________________________________________________________________
______________________________________________________________________________
______________________________________________________________________________
______________________________________________________________________________
1-21
LESSON 1
1-22
Describing data
2
Describing data
Introduction
Key terms The Describe function in the ArcPy site package returns an object that
contains various properties on the data element being described.
Describe function
Types of data that can be described include geodatabases, feature
Describe object classes, tables, rasters, network datasets, topology, geometric
networks, shapefiles, toolboxes and tools, folders, coverages, layer
files, map documents, and many more.
These Describe object properties can be used within a script to report
the values, can make conditional decisions that control the flow of the
script, and can function as input parameters to geoprocessing tools.
During this lesson, you will look at the Describe object properties that
are returned for feature classes, tables, rasters, workspaces, and
layers.
Topics covered
Learning objectives
2-1
LESSON 2
Figure 2.1
The arcpy.Describe
function.
The Describe object has properties that contain descriptive values for
the data element being described. For example, if you were
describing a workspace, you might be interested in knowing if the
workspace is file-based, a local geodatabase, or a remote
geodatabase. If you were working with a feature class, you might
need to know what type of geometry it can store.
These properties can be used to help you write code that can make
decisions based on a property's value. If you were tasked with writing
ArcGIS Help Library:
a script that creates a monthly inventory report on the contents of
Describe (arcpy)
your organization's geodatabases, the Describe object properties
could be used to supply the values for the report. The Describe
object is dynamic, so the properties returned are for the data element
being described. This could include the geodatabase itself, feature
classes, tables, rasters, network datasets, and more. The data element
being described is not limited to just geodatabase elements.
2-2
Describing data
2-3
LESSON 2
Figure 2.2
Process of a feature class
being passed to the
Describe function.
2-4
Describing data
featureType String Information on the feature type being stored in the feature class.
Feature classes storing points, lines, and polygons return a value of
"Simple".
shapeType String The geometry shape type. Values are Point, Polygon, Polyline,
MultiPoint, and MultiPatch.
Table 2.2
Table properties
OIDFieldName String The name of the ObjectID field, if it exists. External tables will not
have an ObjectID field.
fields List of field A list of Field objects for the table. Each field object in the list will
objects have properties about the field.
Table 2.3
2-5
LESSON 2
Dataset properties
canVersion Boolean For remote datasets, a True value indicates that the dataset
can be versioned.
datasetType String Indicates the type of dataset that is being described. Some
possible values: FeatureDataset, FeatureClass,
RasterDataset, Terrain, Locator, and Table (this is not an
exclusive list).
extent Extent An extent object whose properties provide the X & Y of the
lower-left and upper-right corners of a rectangle bounding
the features in the dataset. There are several spatial
comparison methods also included in the extent object
(such as contains, crosses, overlaps, touches).
isVersioned Boolean For remote datasets, True indicates the dataset is versant.
MExtent String If the dataset is m-value enabled, it will contain the MMin
and MMax values.
ZExtent String If the dataset is z-value enabled, it will contain the ZMin and
ZMax values.
Table 2.4
2-6
Describing data
Figure 2.3
Process of a raster dataset
being passed to the
Describe function.
2-7
LESSON 2
2-8
Describing data
2-9
LESSON 2
Fill-in-the-blank
Provide the missing information needed to complete the script.
Describe a table
# This script describes a table
# from the World.gdb.
# Import the ArcPy site package and
# set the workspace environment
import arcpy
arcpy.env.workspace =
"C:\Student\PYTH\Describing_data\World.gdb"
# Describe the Lakes feature class
desc = arcpy.Describe("Lakes")
# Display the field name and data type
# for each field
fldList = desc._________
for ____ in fldList:
print "{} : {}".format(
fld.______, fld.______)
2-10
Describing data
Describe a raster
# This script describes the erelev raster from
# the Tahoe\Emer folder.
# Import the ArcPy site package and
# set the workspace environment
import arcpy
arcpy.env.workspace = "C:\Student\PYTH" + \
"\Describing_data\Tahoe\Emer"
desc = arcpy.Describe("Erelev")
# Print data Type, should be "RasterDataset"
print "Describe Data type is: " + desc.dataType
# Print number of bands, format and compression
print "Band count: {}, format: {}, " + \
compression: {}".format(
desc.__________, desc.___________, desc._________)
# Print spatial reference name
print desc.________________.name
2-11
Describing data
Figure 2.4
Results of executing code
to clip rasters by an extent
object.
2-13
LESSON 2
a In PyScripter, from the File menu, select New > New File.
b In the New File dialog box, select Header Script, and then click Create.
c Add information inside the header that describes your script. Be sure to update the Name to
MyDescribe_schools.py
d Add code to import the ArcPy module and set the workspace to the
C:\Student\PYTH\Describing_data\Corvallis.gdb geodatabase.
Next, you will work with the object returned from the Describe function.
f Enter the following line of code in your script to describe the Schools feature class:
desc = arcpy.Describe('Schools')
The desc variable contains the Describe object returned from the arcpy.Describe function.
Next, you will use the str.format() method to format string values that will be output to the
print statement.
The str.format() method is detailed in the Python 2.7 documentation, Section 7.1.3 -
Format String Syntax.
The str.format() method performs a string formatting operation on the text string passed to
the print statement by using what are called replacement fields delimited by braces {}.
Each set of curly braces in the text string indicates a replacement field and all text outside of the
curly braces is considered literal text. An optional numeric value can be placed inside of the curly
2-14
Describing data
braces, which indicates its index position in the tuple that is passed as the argument to the
format() method.
Code samples for using the str.format() method are in the C:\Student\PYTH\
Describing_data\Samples folder.
g Using your knowledge of the str.format() method and the Describe object, add code to
report on the Describe object values. Use a print statement and the str.format()
method to perform a string formatting operation on the Describe objectshapeType and
datasetType properties:
print "Name: {} Shape: {} Type: {}".format(desc.name,
desc.shapeType, desc.datasetType)
h Add a for-in loop to the script to print out the Python list of field objects names:
for fld in desc.fields:
print "\t{}".format(fld.name)
You can use escape sequences in strings to control the output from the print function. A
'\t' will insert a horizontal tab in the string, a '\n' will insert a line feed in the string. A
table listing escape sequences is detailed in the Python v2.7 documentation in Section
2.4.1 - String literals.
Next, you will write code to describe the Corvallis geodatabase. The City needs information on
the geodatabase type, the release number, and the file path.
k Describe the Corvallis geodatabase. Assign the Describe object to a variable named descGDB.
l Using a print statement, report the workspace type, release number, and file path.
Verify that your code for describing the Corvallis geodatabase looks like the following:
# Describe the Corvallis geodatabase.
descGDB = arcpy.Describe(arcpy.env.workspace)
2-15
LESSON 2
m Add code to the script that will inform the end user that the script has completed.
n Check your script for syntax errors, and then run your script.
o Upon successful execution of your script, close the script in PyScripter, but do not close
PyScripter.
d Add code to import the ArcPy module, and then set the workspace to the
C:\Student\PYTH\Describing_data\Corvallis.gdb geodatabase.
For the next part of this script, you will work with a Python list of feature class names. The
arcpy.ListFeatureClasses() function will be used to create the list.
e Enter the following line of code into your script to create the list of feature class names:
fc_list = arcpy.ListFeatureClasses()
A for-in loop will be used to iterate through the list of feature class names returned from the
arcpy.ListFeatureClasses() function. Inside the for-in loop, you will pass each name to the
Describe function.
2-16
Describing data
g In the ArcGIS Help Library, search for the Get Count (Data Management) geoprocessing tool.
Hint: In ArcMap, use the Help menu or the Search window; or, in a browser, go to the ArcGIS
Resource Center (resources.arcgis.com).
______________________________________________________________________________
h Within the for-in loop, add a line of code to the script that assigns the return object from
the arcpy.GetCount_management() function to a variable named featCount. Be sure to
pass the name variable to the in_rows parameter for the tool.
For the final part of the script, you will write code to print the following:
• Name of the feature class
• Shape type supported by the feature class
• Spatial reference name
• Number of rows in the feature class
i Within the for-in loop, add the following line of code to the script to print the variable
values using the str.format() method:
print "Name: {} Shape: {} SR: {} Count: {}".format(
desc.name, desc.shapeType, desc.spatialReference.name, featCount)
j Add a new line of code at the bottom of the script to print a message indicating that the script
is complete.
2-17
LESSON 2
fc_list = arcpy.ListFeatureClasses()
for name in fc_list:
desc = arcpy.Describe(name)
featCount = arcpy.GetCount_management(name)
print "Name: {} Shape: {} SR: {} Count: {}".format(
desc.name, desc.shapeType, desc.spatialReference.name, featCount)
print "Script completed"
l Save your script, check the code syntax, and run the script.
m After your script runs successfully, close it, and leave PyScripter open.
In your script, you wrote code to work with a list of feature classes. For each feature class in the
list, you described the feature class and determined the number of features using a
geoprocessing tool. You then reported on the feature class describe properties and the feature
count for each feature class.
In the next step, you will write a script that uses Describe object properties as input to a
geoprocessing tool.
In preparation for your planned hike in the Lake Tahoe area, you will work with the set of rasters
provided by the county. Your task is to write a script that will clip the rasters to the extent of the
erelev raster. The clipped rasters will be used later to produce maps of the hiking area.
a In the ArcGIS Help Library, search for a geoprocessing tool that can clip raster datasets to
create a spatial subset of the input raster. When viewing the results, exclude from
consideration the geoprocessing tools that require the Spatial Analyst extension.
______________________________________________________________________________
______________________________________________________________________________
2-18
Describing data
4. For the rectangle parameter of the tool, what are the four coordinates that need to be
specified (list them in order)?
______________________________________________________________________________
f Add a line of code to assign the extent object from the Describe object to a variable named
rasExtent.
The extent object will provide the rectangle parameter for the Clip tool.
g Enter the following line of code in your script to obtain a list of rasters in the current
workspace:
ras_list = arcpy.ListRasters()
Listing rasters and feature classes are covered in the next lesson.
A for-in loop will be used to iterate through the list of raster datasets returned from the
arcpy.ListRasters() function. Inside the for-in loop, you will pass each raster name to the
geoprocessing tool that clips the rasters.
i Inside the for-in loop, add code to call the Clip (Data Management) geoprocessing tool.
2-19
LESSON 2
j Using your answers to the questions earlier in this step, pass the three required parameters to
the arcpy.Clip_management tool. For the rectangle parameter, use the string equivalent of
the object to pass the four required values (as in str(rasExtent) ). For the output raster
name, concatenate _clip to the name variable using the str.format() method (as in
'{}_clip'.format(name)).
l For the final line of code in the script, add a print statement to inform the end user the script
is completed.
n In either ArcCatalog or the ArcMap Catalog window, confirm that the clipped rasters were
created in the C:\Student\PYTH\Describing_data\Tahoe\All workspace.
You may need to create a new folder connection to the C:\Student\PYTH folder in your
Catalog window.
2-20
Describing data
5. Why did all of the clipped rasters end up in the Tahoe\All folder?
______________________________________________________________________________
o If you are not going to complete the Challenge step, close all open applications.
2-21
LESSON 2
15 minutes
The time to complete the Challenge step is not included in the estimated exercise time of
50 minutes.
Using datasets of your choice, or data you have brought with you, write a script to describe the
following:
• All of the feature classes in your data folder or geodatabase. Report on the Describe
object properties of your choice.
• A dataset of choice (either a feature class or feature dataset). Report on the name of the
spatial reference (spatialReference.name) and the extent of the dataset.
2-22
Describing data
Lesson review
______________________________________________________________________________
______________________________________________________________________________
______________________________________________________________________________
______________________________________________________________________________
______________________________________________________________________________
______________________________________________________________________________
______________________________________________________________________________
______________________________________________________________________________
______________________________________________________________________________
______________________________________________________________________________
3. How can you obtain the name of a spatialReference for a feature class?
______________________________________________________________________________
______________________________________________________________________________
2-23
LESSON 2
4. For the rectangle parameter of the tool, what are the four coordinates that need to be
specified (list them in order)?
X-Minimum, Y-Minimum, X-Maximum, Y-Maximum
5. Why did all of the clipped rasters end up in the Tahoe\All folder?
The arcpy.Clip_management tool works with the arcpy.env.workspace setting if an
explicit path is not set for the output raster.
2-24
Describing data
The challenge code should include code for looping through all the feature classes in a folder or
geodatabase. Values from the Describe object returned should be printed to the Python
Interpreter window.
The challenge code should also include code for returning the spatial reference name and the
dataset extent values to the Python Interpreter window.
2-25
Automating scripts with lists
3
Automating scripts with lists
Introduction
Key terms One of the primary tasks in scripting is automating the processing of
data with a list of datasets. The ArcPy site package has many List
iterate
functions that are built to return Python lists for different types of
data. In this lesson, you will explore these ArcPy List functions.
Topics covered
Learning objectives
3-1
LESSON 3
The ArcPy site package provides a number of List functions that return
a list of values. These List functions can provide you with a list of
feature class names in a geodatabase, shapefile names in a system
folder, table names in a geodatabase, field names in a table or
feature class, and many other lists.
The scripts that you write can iterate through the list and perform
defined tasks. This means that the task will be performed on each
item in the list. For example, you could run a geoprocessing tool on
an item or simply report the name to the application.
Figure 3.1
The ArcPy List functions.
3-2
Automating scripts with lists
3-3
LESSON 3
Many of the listed functions accept a wildcard for filtering names, and
require that the current workspace is set in the environment settings
before using the function. The wildcard parameter defines a name
filter for the function, so only the names that pass through the filter
are stored in the list created by the function. Keywords can also be
provided to restrict the supported types for the function to a specific
type. If not specified in the function's parameter, or if the keyword
'All' is specified, all supported types for the function are returned to
the list.
To work with your list, use a for loop to iterate through the list one
item at a time. The list can also be manipulated with standard list
ArcGIS Help Library:
methods such as sort, append and reverse.
Create lists of data
3-4
Automating scripts with lists
____________________________________________________________
____________________________________________________________
____________________________________________________________
3. Provide a list of ArcPy List functions that must have the current
workspace environment set before the function can be used.
____________________________________________________________
3-5
LESSON 3
Figure 3.2
Workflow to automate
tasks using ArcPy list
functions.
3-6
Automating scripts with lists
List data
Using the script comments, fill in the code that is missing in the three
incomplete scripts. Use the workbook and ArcGIS Desktop Help
Library resources to complete the activity.
List datasets:
# This script creates a Python list of feature
# datasets from the World.gdb geodatabase.
# A for-in loop is used to iterate through the
# list and print the dataset name(s)
# to the Python Interpreter window
import arcpy
arcpy.env.workspace =
"C:\Student\PYTH\Automating_scripts\World.gdb"
# Fill in the blanks
dataset_list = arcpy.________()
for dataset in ______:
print ______
3-7
LESSON 3
3-8
Automating scripts with lists
Figure 3.3
Results of the created
buffer featured classes
displayed in the map.
3-9
LESSON 3
Figure 3.4
Workflow to document
field properties for a table
or feature class.
Figure 3.5
Workflow for automating a
geoprocessing task on a
list of feature classes.
3-10
Automating scripts with lists
a In PyScripter, create a new header script named MyListFieldProperties.py and save it to the
C:\Student\PYTH\Automating_scripts folder.
The os.path.join() function joins two items together intelligently, with a directory
separator between the two items.
e In the ArcGIS Help Library, search for Listing data. Choose the Create lists of data help page.
______________________________________________________________________________
f Using the answer, write code using the ArcPy List function to create a list of field names on the
MajorAttractions feature class. Assign the list returned from the function to a variable
named field_list, as in:
field_list = arcpy.ListFields("MajorAttractions")
3-11
LESSON 3
g Do not close the ArcGIS Help Library. You will be using it later in this exercise to help develop
your script.
Next, you will write code in the script to open a text file for write access, and then add a header to
the file contents.
h Add the following code to the script to open the text file and write two header lines:
txtFile = open(os.path.join(wksp,"MajorAttractions.txt"), "w")
txtFile.write("MajorAttractions field information" + "\n")
txtFile.write("----------------------------------" + "\n")
You should always concatenate a newline character ('\n') to the end of the string value
before passing the string to the file.write() method. The newline character will
indicate the end of the line.
The next task in the script is to write each field's name, type, and length properties to the text file.
i Create a for loop on field_list, with the item value being passed to a variable named
field.
j Within the loop, use the str.format() function to assemble a string value containing the
Name, Type, and Length properties of the field object. Assign it to a variable named line:
line = "Name: {}, Type: {}, Length: {}\n".format(
field.name, field.type, field.length)
k Add code to pass the line variable as the parameter to the write() method on txtFile, as
in:
txtFile.write(line)
Your final task is to close the text file and provide a message stating the script is completed.
n Use txtFile's close() method to close the text file. No parameter is passed to the method.
3-12
Automating scripts with lists
q Save your script. Check the script syntax, fix any errors and then run your script.
r In the Python Interpreter window, press the Enter key to obtain the prompt.
s Type: os.popen(os.path.join(wksp,"MajorAttractions.txt"))
u Close the script, but be sure to leave PyScripter open for the next step.
3-13
LESSON 3
a Create a new header script named MyBufferSanDiegoFC.py, and then save it to the C:\
Student\PYTH\Automating_scripts folder.
c Return to the Create lists of data ArcGIS Help page to answer the next question.
2. Which of the ArcPy functions returns a list of feature classes in the current workspace?
______________________________________________________________________________
d Using your answer, write code to use the arcpy List function that creates a list of feature class
names in the SanDiego geodatabase, assigning the list returned from the function to a
variable named fc_list.
e Create a for loop on fc_list, with the item value being passed to a variable named
featClass.
f Inside the loop, pass featClass as the parameter value to the arcpy.Describe() function.
Assign the describe object returned from the function to a variable named desc.
g While still in the loop, write code using the if-elif statement to set a variable named
buffDist to the value:
• if desc.shapeType is equal to 'Point' the buffDist is '1000 feet'
• elif desc.shapeType is equal to 'Polyline' the buffDist is '500 feet'
• elif desc.shapeType is equal to 'Polygon' the buffDist is '-750 feet'
3-14
Automating scripts with lists
h Below the if-elif statement, and while still in the loop, add code to the script to run the
arcpy.Buffer_analysis() tool, setting these parameters:
• in_features = featClass
• out_feature_class = featClass + "_Buff"
• buffer_distance_or_field = buffDist
j Outside of the loop, add a line that prints a message stating the script is completed.
k Check the script syntax, fix any errors and then run your script.
3-15
LESSON 3
a In ArcMap, open the Catalog window and navigate to the Automating_scripts folder.
b Expand the SanDiego geodatabase and verify that the script created the buffered feature
classes.
c From the Catalog window, drag some of the buffered feature classes onto the map.
d Using the tools available in ArcMap, verify that the script buffered the features with the correct
distance.
e Close ArcMap when you are done. If you would like, you can save the mxd.
3-16
Automating scripts with lists
Lesson review
______________________________________________________________________________
______________________________________________________________________________
______________________________________________________________________________
______________________________________________________________________________
3. Write a line of code that returns a list of integer field names from a table.
______________________________________________________________________________
______________________________________________________________________________
______________________________________________________________________________
______________________________________________________________________________
3-17
LESSON 3
2. The ListFields() function returns a list of items containing field objects. What are some
of the field object properties that you can access?
Field object properties returned include name, aliasName, isNullable, type, required,
length, precision, scale, domain, editable, and baseName.
3. Provide a list of ArcPy List functions that must have the current workspace environment set
before the function can be used.
ListDatasets(), ListFeatureClasses(), ListTables(), ListFiles(), ListRasters(), and
ListWorkspaces().
Exercise 3: Automate scripts with the ArcPy List functions (page 3-9)
1. Which of these functions returns a list of fields?
ListFields(dataset, wild_card, field_type) returns a list of fields.
2. Which of the ArcPy functions returns a list of feature classes in the current workspace?
ListFeatureClasses(wild_card, feature_type) returns a list of feature classes in the
current workspace.
3-18
Working with Selections
4
Working with Selections
Introduction
Topics covered
Learning objectives
4-1
LESSON 4
Figure 4.1
Workflow for typical
selection task in ArcMap.
4-2
Working with Selections
Table 4.1
Term Description
4-3
LESSON 4
4-4
Working with Selections
In the ArcGIS Desktop Help Library, refer to the following help pages
to fill out the table and answer the questions:
Use the search field to
search for these topics in • An overview of the Layers and Table Views toolset
the help. • Creating and using layer selections
1. Complete the following table. (The first row has been filled out for
you.)
Tools that create or manage feature layers and table Creates output Requires feature
views. feature layer or layer or table view
table view? for input?
Table 4.2
____________________________________________________________
____________________________________________________________
4-5
LESSON 4
Figure 4.2
Workflows for working
with a selection.
4-6
Working with Selections
Tool syntax:
arcpy.MakeFeatureLayer_management(in_features,
out_layer, {where_clause},
{workspace}, {field_info})
4-7
LESSON 4
4-8
Working with Selections
To maintain new field names, the feature layer or table view needs to
be written out to a new dataset using the
ArcGIS Help Library:
arcpy.CopyFeatures_management() or the
FieldInfo (arcpy)
arcpy.CopyRows_management() tool.
The FieldInfo object provides methods and properties for modifying
field schema in layers and table views, and is typically passed as an
optional parameter to the MakeFeatureLayer tool or the
MakeTableView tool. The Describe object returned from the
arcpy.Describe function will provide the FieldInfo object for a feature
layer or table view if defined when the layer or view were created.
Syntax:
arcpy.FieldInfo()
4-9
LESSON 4
Method:
addField(field_name, new_field_name, visible,
split_rule)
4-10
Working with Selections
arcpy.AddFieldDelimiters function
Table 4.6
Parameter Description
field The field name for which the field delimiters will be
added.
4-11
LESSON 4
Determining a workflow
When writing a script that uses feature layers and selections, it may be
beneficial to break the script down into sections in order to determine
the workflow.
Sample scenario:
The City of Wilson has been asked to provide a count of all
alcohol-related crimes near the Historical District. The parameters
provided to perform the tasks are:
• Locate all of the restaurants that are within 1000 feet of the
Historical District that serve alcohol.
• Locate all alcohol related crimes that are within 500 feet of the
selected restaurants.
• Report on the number of selected alcohol-related crimes.
Figure 4.3
Script workflow for
locating crimes within 500
feet of restaurants that
serve alcohol and are
within 1000 feet of the
City's Historical District.
4-12
Working with Selections
4-13
Working with Selections
Figure 4.4
High-level workflow for
exercise.
4-15
LESSON 4
Your next task in the workflow is to add field delimiters to the TYPE and ESTAB fields. These fields
will be used in constructing two SQL expressions.
When working with geoprocessing tools in your scripts, you can skip optional parameters
by specifying each parameter name and the value to assign. Some tools will have a mix of
required and optional parameters specified, but not all optional parameters may be
needed for the desired tool result.
4-16
Working with Selections
The next task is to assemble the two SQL expressions, which will be used later in the script as the
where_clause parameters for the arcpy.MakeFeatureLayer_management function.
The first SQL expression will be used for creating the Maritime feature layer, and the second SQL
expression will be used to create the Historic Attractions feature layer.
In the next exercise step, you will apply the SQL expressions to the
arcpy.MakeFeatureLayer_management function.
f Save your script, check the script syntax, and fix any errors.
a In your script, add code to create the Maritime layer using the
arcpy.MakeFeatureLayer_management function:
• Pass these parameters:
• "Climate" for the in_features parameter
• "MaritimeLyr" for the out_layer parameter
• maritimeSQLExp variable for the where_clause parameter
4-17
LESSON 4
c Save your script, check the script syntax, and fix any errors.
c Add code to print the number of selected features, which is the value in featCount.
If you would like to check for valid results, you can run your script at this time. Running the
script should result in a selected feature count of eight.
Remember that the feature layers will remain in memory as long as the PyScripter session is
running, or until you use the arcpy.Delete_management function to remove them.
4-18
Working with Selections
For the final task in the script, the feature layers will be removed from memory.
b Add code to call the arcpy.Delete_management function twice, once for each feature layer
created in the script. Pass the name of the feature layer to the tool's parameter.
c Add a final line of code to print that the script has completed.
d If you ran your script at the end of Step 3, type these two commands at the Python Interpreter
window to remove the feature layers in memory:
arcpy.Delete_management("MaritimeLyr")
arcpy.Delete_management("HistoricLyr")
e Check the script syntax, fix any errors, and then run your script.
f Use ArcCatalog to verify that the MaritimeAttractions feature class has been created.
4-19
LESSON 4
Lesson review
1. List two geoprocessing tools that must use a feature layer to create selections.
______________________________________________________________________________
______________________________________________________________________________
2. What kind of schema changes can you make on a field with a FieldInfo object?
______________________________________________________________________________
______________________________________________________________________________
______________________________________________________________________________
3. If a field is set to HIDDEN in a FieldInfo object, will the field be available in the output
feature layer?
______________________________________________________________________________
______________________________________________________________________________
______________________________________________________________________________
4-20
Working with Selections
Tools that create or manage feature layers and table Creates output Requires feature
views. feature layer or layer or table view
table view? for input?
2. What is the main benefit of using a feature layer as input to a geoprocessing tool?
Only the selected features will be used.
3. What geoprocessing tool can you use to make a feature layer permanent?
The CopyFeatures_management tool.
4-21
Working with Cursors
5
Working with Cursors
Introduction
Key terms Accessing data in feature classes and tables is the starting point for
many data management and analysis workflows. A cursor is a data
cursor objects
access object that can be used to iterate over a set of data in a table
insert cursor or insert new rows into a table. Many workflows include adding new
data, updating existing data, or working with a subset of data to limit
search cursor
which feature values are accessed and updated. The cursor allows you
update cursor to script and automate these types of data access tasks.
In the previous lesson, you learned about working with selections and
subsets of data, which are used in geoprocessing tools and to create
new feature classes. In this lesson, you will work with the da cursors to
read, update, and populate feature classes and tables.
Topics covered
• arcpy.da cursors
• Search cursor
• Update cursor
• Insert cursor
Learning objectives
5-1
LESSON 5
Throughout this lesson, you will explore working with ArcPy cursor
objects, which are accessed from the arcpy.da module. These cursors
ArcGIS Help Library: What
are designed to allow high-performance access to field contents in
is the data access module?
feature classes and tables, update field contents, and populate new
(arcpy.da)
rows.
Figure 5.1
The arcpy.da cursor tasks.
5-2
Working with Cursors
5-3
LESSON 5
SearchCursor syntax:
arcpy.da.SearchCursor(in_table, field_names,
(where_clause}, {spatial_reference},
(explode_to_points}, {sql_clause})
SearchCursor methods
Table 5.3
method Description
next() Returns the next row in the cursor as a tuple of field values
in the order the fields were specified in the cursor.
5-4
Working with Cursors
5-5
LESSON 5
5-6
Working with Cursors
UpdateCursor syntax:
arcpy.da.UpdateCursor(in_table, field_names,
(where_clause}, {spatial_reference},
(explode_to_points}, {sql_clause})
arcpy.da.UpdateCursor parameters
Table 5.5
Parameter Description
5-7
LESSON 5
UpdateCursor methods
Table 5.6
method Description
5-8
Working with Cursors
InsertCursor syntax:
arcpy.da.InsertCursor(in_table, field_names)
arcpy.da.InsertCursor parameters
Table 5.7
Parameter Description
InsertCursor method
Table 5.8
method Description
5-9
LESSON 5
Exclusive lock
• Applied when changes are made to a table or feature class,
either to field values or to the schema.
• Examples of when an exclusive lock is applied: Using an
UpdateCursor or InsertCursor in a Python IDE, saving edits to a
feature class in ArcMap, or changing the schema in ArcCatalog.
• Update cursors and Insert cursors apply an exclusive lock if
successfully created.
• Always del the InsertCursor and UpdateCursor objects to
remove the exclusive database lock.
5-10
Working with Cursors
The arcpy.da.Editor class provides you with the ability to use edit
sessions to manage database transactions. Edits are temporary until
With ArcSDE
they are saved, at which time they are committed to the dataset.
geodatabases, an edit
session can be started The arcpy.da.Editor class supports edit operations on shapefiles,
with either versioned or personal and file geodatabases, and ArcSDE geodatabases.
nonversioned datasets.
Here is a typical workflow for using the arcpy.da.Editor:
• Set arcpy.env.workspace to the dataset to be edited.
• Create an editor object from the arcpy.da.Editor class.
• Call the startOperation method on the editor object.
• Call the startEditing method with the following parameters:
• with_undo (Boolean): enables or disables the undo and redo
stacks in an edit session. If working in a versioned dataset,
the undo and redo stacks are always enabled.
• multiuser_mode (Boolean): sets editing control in
nonversioned or versioned environment. If set to False, you
have full control of editing a nonversioned or versioned
dataset.
• Perform the editing task(s) with the cursor or geoprocessing
tool.
• Call the stopOperation method on the editor object.
• Stop the edit session with the following parameter:
• Boolean True to save the changes
• Boolean False to discard the changes
5-11
LESSON 5
arcpy.da.Editor syntax:
arcpy.da.Editor(workspace)
arcpy.da.Editor parameters
Table 5.9
The arcpy.da.Editor class Parameter Description Data type
arcpy.da.Editor methods
Table 5.10
Method Description Data
type
5-12
Working with Cursors
5-13
LESSON 5
5-14
Working with Cursors
5-15
LESSON 5
a In the ArcGIS Help Library, navigate to the Accessing data using cursors help page.
Hint: Desktop > Geoprocessing > Python > Accessing geographic data in Python > Working
with cursors in Python > Accessing data using cursors.
b Click the link for each cursor in the Cursor table. Take a few moments to examine the
summary, discussion, and syntax for the InsertCursor, SearchCursor, and UpdateCursor.
______________________________________________________________________________
______________________________________________________________________________
______________________________________________________________________________
3. What method on the UpdateCursor can be used to remove a row from the feature class or
table?
______________________________________________________________________________
4. For the InsertCursor, what is passed to the row parameter of the insertRow() method?
______________________________________________________________________________
5-16
Working with Cursors
Hint: The \n can be used in the print statement as a newline character, as in:
print "{0}\n{1}\n{2}, CA {3}\n".format(row[0],row[1],row[2],row[3])
The list of values in the row object are in the same order as the field names passed to
the cursor.
If you need additional assistance with the script, the MyAttractions.py exercise solution
script is located in the C:\Student\PYTH\Cursors\Solution folder.
d Check your script for syntax errors, then run the script.
e In the Python Interpreter window, scroll to the end of the list of addresses.
5-17
LESSON 5
______________________________________________________________________________
______________________________________________________________________________
You have just been handed a request to add a new ACRES field to the Parcel feature class and
update the values in the new field. You will write a script to perform the workflow.
a Using the ArcGIS Help Library, search for a geoprocessing tool that will add a new field to a
feature class or table. Use your research results to help answer the following question.
6. What geoprocessing tool located in the Data Management toolbox was returned by the
Desktop Help Search?
______________________________________________________________________________
5-18
Working with Cursors
If you need additional assistance with the script, the MyParcel_Acres.py exercise solution script is
located in the C:\Student\PYTH\Cursors\Solution folder.
e Check your script for syntax errors, then run the script.
g Open ArcCatalog and view the updated table in the Corvallis geodatabase. Verify that the
field has been added and the ACRES field is populated.
5-19
LESSON 5
Your current task is to create a new feature class containing a "NAME" field. X&Y values will be
used to populate the SHAPE field. You will write the script using the da.InsertCursor to accomplish
the task.
a Create a new Python script named MyPopulate_XY.py and save it to the C:\Student\PYTH\
Cursors folder.
c Import the arcpy module and set the workspace environment setting to
C:\Student\PYTH\Cursors\Corvallis.gdb.
f Assign the list to a variable named rowValues. Use the following table for the values.
Name X Y
g Use the appropriate geoprocessing tool to create a new point feature class. Pass these
parameters to the geoprocessing tool:
• arcpy.env.workspace for the out_path parameter
• "CountyPNT" for the out_name parameter
• "POINT" for the geometry_type parameter
Hint: In the ArcGIS Help Library, search for create feature class to find a geoprocessing tool
that can create a feature class.
5-20
Working with Cursors
h For the new CountyPNT feature class, use the appropriate geoprocessing tool to add a new
field, with a field_name of "NAME" and a field_type of "TEXT".
j Assign the cursor object returned from the InsertCursor to a variable named iCur.
Hint: A with statement cannot be used for an arcpy.da.InsertCursor()
k Iterate through rowValues using a for-in loop, returning each item in rowValues to a
variable named row.
• Call the insertRow() method on iCur, passing the row object to the method's
argument.
If you need additional assistance with the script, the MyPopulate_XY.py exercise solution script is
located in the C:\Student\PYTH\Cursors\Solution folder.
m Check your script for syntax errors, then run the script.
n Verify the new feature class has been created in the Corvallis geodatabase and that it contains
four rows.
The new feature class did not have a spatial reference defined when it was created. If you
would like to assign a spatial reference to the feature class, you can use the spatial
reference of the Parcel feature class in the arcpy.DefineProjection_management tool.
5-21
LESSON 5
Lesson review
1. When working with the da cursors, which Python statement can be used to automatically
close the cursor?
a. A for-in loop
b. A range loop
c. A with loop
2. Which token can be used with the da cursor to efficiently return the X&Y values of a point
feature?
______________________________________________________________________________
______________________________________________________________________________
3. Write a single line of code to return a sorted cursor of descending LAND_VALUE values
from the Corvallis Parcel feature class.
______________________________________________________________________________
______________________________________________________________________________
______________________________________________________________________________
5-22
Working with Cursors
3. What method on the UpdateCursor can be used to remove a row from the feature class or
table?
The deleteRow() method.
4. For the InsertCursor, what is passed to the row parameter of the insertRow() method?
A tuple of values in the order of the fields specified in the cursor's field_names
parameter.
6. What geoprocessing tool located in the Data Management toolbox was returned by the
Desktop Help Search?
The Add_Field_management tool.
5-23
Working with Geometry objects
6
Working with Geometry
objects
Introduction
Key terms In many geoprocessing workflows, you will run tools that work with
coordinate and geometry information. The geoprocessing tools that
geometry list
you will use may accept features from a feature layer or feature class
geometry object as input to the tool. These same tools will also accept geometry
objects as input in place of features.
Geometry objects that can be created in memory include Geometry,
MultiPoint, PointGeometry, Polyline, and Polygon. These can be
empty geometry objects or can be populated with coordinate pairs of
X,Y values.
Topics covered
Learning objectives
6-1
LESSON 6
Figure 6.1
Workflows for creating
geometry objects.
6-2
Working with Geometry objects
Figure 6.2
Creating a Point object.
6-3
LESSON 6
Syntax:
arcpy.Point({X},{Y},{Z},{M},{ID})
6-4
Working with Geometry objects
Figure 6.3
Creating a PointGeometry
object.
Syntax:
arcpy.PointGeometry(inputs, {spatial_reference},
{has_z}, {has_m})
arcpy.PointGeometry parameters
Table 6.2
Parameter Description
6-5
LESSON 6
Figure 6.4
Creating a Polyline object.
6-6
Working with Geometry objects
Syntax:
arcpy.Polyline(inputs, {spatial_reference},
{has_z}, {has_m})
arcpy.Polyline parameters
Table 6.3
Parameter Description
6-7
LESSON 6
Figure 6.5
Creating a Polygon object.
6-8
Working with Geometry objects
Syntax:
arcpy.Polygon(inputs, {spatial_reference},
{has_z}, {has_m})
arcpy.Polygon parameters
Table 6.4
Parameter Description
6-9
LESSON 6
Syntax:
arcpy.Geometry(geometry, inputs, {spatial_reference},
{has_z}, {has_m})
arcpy.Geometry parameters
Table 6.5
Parameter Description
• point
• multipoint
• polyline
• polygon
6-10
Working with Geometry objects
Example:
import arcpy
arcpy.env.workspace = "C:\MyData\MyProject.gdb"
g = arcpy.Geometry()
geomList = arcpy.CopyFeatures_management(
"Railroads", g)
length = 0
for geom in geomList:
length += geom.length
print "Total length in miles: {0}".format(
round(length / 5280, 2))
6-11
LESSON 6
Example:
partOne = arcpy.Array([arcpy.Point(5997624.6225,
2069868.8208),
arcpy.Point(5997674.94199,
2069833.81741)])
partTwo = arcpy.Array([arcpy.Point(5997616.44497,
2069862.32774),
arcpy.Point(5997670.57373,
2069824.67456)])
ary = arcpy.Array([partOne, partTwo])
multiPartPolyline = arcpy.Polyline(ary)
print multiPartPolyline.partCount
6-12
Working with Geometry objects
Figure 6.6
Constructing a multipart
polygon geometry object.
6-13
LESSON 6
Figure 6.7
An UpdateCursor or
InsertCursor is used to
pass geometry to Shape
field.
Code examples:
ArcGIS Help Library:
# Writing geometries with an arcpy.da.InsertCursor
Writing geometries
cursor = arcpy.da.InsertCursor(featClass, "SHAPE@")
ary = arcpy.Array([arcpy.Point(9,11),
arcpy.Point(9,8),
arcpy.Point(6,8),
arcpy.Point(6, 11)])
polygon = arcpy.Polygon(array)
cursor.insertRow([polygon])
del cursor
# Updating geometries with an arcpy.da.UpdateCursor
exp = """ "Name" = 'Balboa Park' """
cursor = arcpy.da.UpdateCursor(featClass2,
"SHAPE@XY", exp)
for row in cursor:
row[0] = arcpy.Point(6285430.0, 1844965.66)
cursor.updateRow(row)
del cursor
# Reading geometries with a arcpy.da.SearchCursor
for row in arcpy.da.SearchCursor("Parks",
["SHAPE@AREA", "NAME"])
area = row[0]
acreage = area / 43560
print("{0} Acres: {1}, Area: [2}".format(
row[1], acreage, row[0])
6-14
Working with Geometry objects
Code example:
# Use an in_memory workspace to store
# geoprocessing tool output as intermediate data.
# Use arcpy.da SearchCursor to access the in_memory
# features
import arcpy
pnt = arcpy.Point(6282633.845, 1838254.582)
#Create geometry object from Point
geom = arcpy.Geometry("Point", pnt)
# Buffer the point and use in_memory
# feature class for output
bufferPnt = arcpy.Buffer_analysis(geom,
"in_memory/bufferPnt","5280 feet")
# Clip meters based on in_memory buffer output
clipMeters = arcpy.Clip_analysis("ParkingMeters",
bufferPnt,"in_memory/clipMeters")
# Access in_memory\clipMeters features using
# an arcpy.da SearchCursor and report the
# meter ID and meter type
with arcpy.da.SearchCursor("in_memory/clipMeters",
["MeterID", "TYPE"]) as cursor:
for row in cursor:
print "ID: {0}, Type: {1}".format(row[0],
row[1])
6-15
LESSON 6
Workflow:
1. Import the ArcPy site package and set the current workspace.
2. Assign feature class names to variables.
3. Use a for-in loop on a SearchCursor to access the Shape X,Y and
NAME field values, where the NAME field contains a value.
4. Report the feature name value and X,Y values.
5. Use a SearchCursor in a with loop to access and report the ID
and SHAPE@AREA values.
6. Use an UpdateCursor to update the Shape X,Y for an existing
feature.
7. Use an empty Geometry object in conjunction with the
arcpy.CopyFeatures tool to output a geometry list containing
Shape geometry objects. Report the total geometry object
length property values.
6-16
Working with Geometry objects
6-17
LESSON 6
______________________________________________________________________________
2. What code would be required to create a new Point object, where X is 2000 and Y is 1000,
assigning the Point object to a variable named pnt?
______________________________________________________________________________
d Start PyScripter and create a new script named MyCreateGeomObjects.py in the C:\Student\
PYTH\Geometry_objects folder.
e Using your answer to the second question, write code to create a new populated Point object
and report the Point object's X,Y coordinates to the Python Interpreter window.
f Check your script for syntax errors, then run the script.
g Verify that the coordinates displayed in the Python Interpreter window match the X,Y
coordinate pair used to create the Point object.
Your next task is to create a new Polyline and Polygon geometry object.
6-18
Working with Geometry objects
h Return to the ArcGIS Help Library, and review the topics for the Polyline and Polygon
geometry classes.
Hint: In the ArcGIS Help Library, search for polyline (arcpy) and polygon (arcpy)
3. What objects must be created in order to populate a new Polyline or Polygon geometry
object?
______________________________________________________________________________
i Use the answer to the above question to write code creating a new Polyline geometry object:
• Create an empty Point object and an empty Array object. Assign the Point object to a
variable named pnt and the Array object to a variable name ary.
• Create a Python list containing the following X,Y coordinate pairs and assign it to a
variable named coords.
X-coordinate Y-coordinate
100 200
200 400
300 700
600 800
500 700
If you need additional assistance or are stuck on an exercise step, you can refer to the
solution scripts in the C:\Student\PYTH\Geometry_objects\Solution folder.
6-19
LESSON 6
j Check your script for syntax errors, then run the script.
k In the PyScripter Python Interpreter window, write the following line of code to report the
pointCount property of the Polyline geometry object:
print "Number of points: {0}".format(polyLine.pointCount)
______________________________________________________________________________
m Check your script for syntax errors, then run the script.
5. What is the value of the pointCount property for the Polygon geometry object?
______________________________________________________________________________
6-20
Working with Geometry objects
b Using the following workflow steps as a guide to writing a script that uses a SearchCursor to
report Shape geometry properties:
• Import the ArcPy site package.
• Set the current workspace environment to
C:\Student\PYTH\Geometry_objects\SanDiego.gdb.
• Create a for loop on the arcpy.da.SearchCursor, passing these parameters:
• "Freeways" for the in_table parameter
• ["SHAPE@XY", "OID@", "SHAPE@LENGTH"] for the field_names parameter
• Assign the return from the SearchCursor to a variable named row.
Verify that your for loop looks like this:
for row in arcpy.da.SearchCursor("Freeways",
["SHAPE@XY", "OID@", "SHAPE@LENGTH"]):
• Inside the loop, report the X, Y, ID, and length properties of the row object to the
Python Interpreter window.
The SHAPE@XY token returns the X,Y values as a tuple. You can slice the row
object to obtain the values (as in row[0][0] for the X value and row[0][1] for
the Y value).
c Check your script for syntax errors, then run the script.
b In ArcMap, note the location of the Balboa Park feature in the MajorAttractions layer.
6-21
LESSON 6
e Using the following workflow steps as a guide to writing a script that uses an
arcpy.da.UpdateCursor to modify the X,Y location of Balboa Park:
• Import the ArcPy site package.
• Set the current workspace environment to
C:\Student\PYTH\Geometry_objects\SanDiego.gdb
• Assign the following variables:
• featClass = "MajorAttractions"
• fields = ["SHAPE@XY"]
• exp = """ "NAME" = 'BALBOA PARK' """
• Create an empty Point object and assign it to a variable named pnt.
• Modify the pnt properties to the following:
• pnt.X = 6285430.0
• pnt.Y = 1844965.66
• Create a with loop on the arcpy.da.UpdateCursor, passing these parameters to the
UpdateCursor:
• featClass for the in_table parameter
• fields for the field_names parameter
• exp for the where_clause parameter
• Assign the cursor to a variable named cur.
Refer to ArcGIS Help Library and search for UpdateCursor (arcpy) to view code
samples. These code samples contain examples of creating an
arcpy.da.UpdateCursor using a with statement.
• Inside the with statement, create a for loop on cur. Assign the rows returned from cur
to a variable named row.
• Within the for-in loop:
• Assign the Point object to row[0]
• Call the updateRow() method on cur, passing row as the parameter.
f Check your script for syntax errors, then run the script.
i If you are going to complete the next optional step, leave ArcMap open and return to
PyScripter.
j If you are not going to complete the next optional step, close ArcMap and PyScripter.
6-22
Working with Geometry objects
In this step, you will write code to create a new feature in the Freeways feature class. In your
script, you will use Point and Array objects, along with a Python List of coordinates to create a new
Polyline geometry object. Working with an arcpy.da.InsertCursor, you will insert the Polyline
into the Freeways feature class.
a In PyScripter, comment the code in your script below the line of code that creates the empty
Point object.
6-23
LESSON 6
b Using the following workflow steps as a guide for adding code to your script that will use an
arcpy.da.InsertCursor to add a new Polyline to the Freeways feature class:
• Assign the following variables:
• featClass2 = "Freeways"
• fields2 = ["SHAPE@","STREET_NAM"]
• fldVal = "Balboa Park Drive"
• Create a new Array object and assign it to ary.
• Using your skills from the first step in the exercise, create a new Polyline geometry
object with the following coordinates, in the form of:
coords = [[<coord1X>, <coord1Y], [<coord2X>, <coord2Y>],
[<coord3X>, <coord3Y], [<coord4X>, <coord4Y>]]
X Y
6284696.620 1844282.464
6284739.145 1844632.515
6284919.091 1844881.011
6285184.726 1845026.683
6285423.068 1845060.988
• Assign the object returned from the arcpy.Polyline class to a variable named
polyLine. Pass ary to the arcpy.Polyline parameter.
• Create a new arcpy.da.InsertCursor and assign the cursor to a variable named cur2.
Pass featClass2 and fields2 to the cursor for the two parameters.
• Call the insertRow method on the cursor, passing polyLine and fldVal as a list to
the method's parameter, in the form of cur2.insertRow([polyLine, fldVal]).
• Add a final line of code to delete the InsertCursor cur2 using the del statement to
remove the exclusive lock on the Freeways feature class.
If you need additional assistance or are stuck on an exercise step, you can refer to the
solution scripts in the C:\Student\PYTH\Geometry_objects\Solution folder.
c Check your script for syntax errors, then run the script.
6-24
Working with Geometry objects
e Confirm that the new feature has been added to the Freeways layer and that the
STREET_NAM value is 'Balboa Park Drive'.
You may need to refresh the view in order to see the new feature.
f Close ArcMap.
g If you have time and would like to work on the final optional step, keep PyScripter open.
Otherwise, close PyScripter.
In this step, you will work with the Corvallis geodatabase, a Polygon geometry object, and a
Geoprocessing tool to clip out the Downtown streets and store them in a separate feature class.
X-coordinate Y-coordinate
1277000.0 344000.0
1283000.0 344000.0
1283000.0 336000.0
1277000.0 336000.0
e Using the correct Clip geoprocessing tool, clip the StPaved feature class against the Polygon
geometry object, creating the new DowntownStreets feature class.
6-25
LESSON 6
Be sure to choose the correct Clip tool—one of the Clip tools only works with
rasters.
f Check your script for syntax errors, then run the script.
h Add the DowntownStreets feature class to the map and choose symbology that will contrast
the downtown streets from the Streets layer.
i In the table of contents, right-click the DowntownStreets layer and select Remove.
k Confirm that the check box to Overwrite the outputs of geoprocessing operations is selected.
m Load the script into the Python window, then press Enter twice to run the script.
o Close PyScripter.
In the exercise, you created Point and Array objects, and Polyline and Polygon geometry objects.
You accessed Shape geometry properties using a SearchCursor, updated the Shape X,Y for an
existing feature using an UpdateCursor, created new features using an InsertCursor, and passed a
geometry object to a geoprocessing tool to extract features to a new feature class.
6-26
Working with Geometry objects
Lesson review
1. To create a Polyline or Polygon geometry object, what two objects must first be created?
______________________________________________________________________________
______________________________________________________________________________
2. List some geometry tokens that efficiently access Shape geometry properties.
______________________________________________________________________________
______________________________________________________________________________
3. Provide a couple of examples in which you would use a geometry object with a
geoprocessing tool.
______________________________________________________________________________
______________________________________________________________________________
______________________________________________________________________________
6-27
LESSON 6
2. What code would be required to create a new Point object, where X is 2000 and Y is 1000,
assigning the Point object to a variable named pnt?
pnt = arcpy.Point(2000, 1000)
3. What objects must be created in order to populate a new Polyline or Polygon geometry
object?
A Point object and an Array object. (A Python List of X,Y coordinate pairs is optional.)
5. What is the value of the pointCount property for the Polygon geometry object?
The value of the pointCount property for the Polygon geometry object is 6.
6-28
Sharing scripts
7
Sharing scripts
Introduction
Key terms Up to this point, you have been writing scripts that are using
hard-coded paths for data and variables with hard-coded values. This
model
works fine in scripts that may be used for one-off workflows or for
parameter when a script operates on the same set of data from time to time.
script There will be times when you would like to share a script with another
user, run a script on data in a different location, or even work through
script tool
a workflow where the input and output parameters would change for
system tool each scenario.
By adding arguments to your scripts, you can make the script more
dynamic, better fit your automation and analysis workflows, and
shareable through Geoprocessing packages and services.
Topics covered
Learning objectives
7-1
LESSON 7
Table 7.1
Term Definition
7-2
Sharing scripts
7-3
LESSON 7
Figure 7.1
The index numbers in the
GetParameterAsText()
functions match the order
of the parameters inside of
the script tool dialog box.
7-4
Sharing scripts
Once your script is dynamic, you can create a script tool that runs
your script. The script tool can prompt the user to provide arguments,
which are passed from the script tool dialog box to your script at
runtime. The dialog box also validates your entries for a match with
each parameter defined for the script tool, and will run only after all
parameters are valid.
The arcpy.GetParameterAsText() function can also accept Command
Line Parameters from PyScripter, which can be extremely useful when
testing your script. In PyScripter, access the Command Line
Parameters dialog box from the Run menu > Command Line
Parameters. In the dialog box, check the box at the top and then
enter the parameter values, separated by spaces. To skip an optional
parameter, simply use a double quote, as illustrated below.
Figure 7.2
The PyScripter Command
Line Parameters dialog
box.
7-5
LESSON 7
7-6
Sharing scripts
7-7
LESSON 7
Figure 7.4
First panel of the Add
Script wizard.
7-8
Sharing scripts
Second panel
Figure 7.5
Second panel of the Add
Script wizard.
7-9
LESSON 7
Third panel
This is where the parameters are set up in the order they are set in the
script. Each parameter has additional properties that can be set.
• Whether the parameter is required or optional.
• Whether the parameter value must already exist (input), must
not exist (output) or is derived from the script execution, such as
a boolean True or False.
Additional parameter properties are available for:
• Applying filters.
• Setting default values.
• Setting environment values that override the current settings.
• Obtaining information from another parameter.
• Applying a layer file to the output data for symbology.
Figure 7.6
Third panel of the Add
Script wizard.
When running your custom tool as a Server tool, your parameters for
input and output data must be set to either FeatureSet or RecordSet.
ArcGIS Help Library:
Working with feature sets
and record sets
7-10
Sharing scripts
Running a script
Once you have attached your script as a custom tool, the next step is
to run your script in ArcGIS Desktop. The script will create a result that
can be shared as a package. You have a couple of choices when
running your script in ArcMap. You can run it as a tool dialog or you
can run it in the Python window.
Figure 7.7
Completed tool dialog.
7-11
LESSON 7
Figure 7.8
Note that the toolbox alias
is part of the tool name,
and the Help panel
displays the tool syntax.
Figure 7.9
Note that the result of
running the tool is
indicated in the Python
window; geoprocessor
messages are displayed in
the Help panel.
The result of running the tool will be stored in the Results window
under Current Results. If the script tool creates a new feature class or
table as a result, the result is added ArcMap's active data frame.
7-12
Sharing scripts
Sharing a script
Before sharing your results, you must return to your custom script tool
and fill out the Item Description. The information you place in the
script tool Item Description is stored as part of the package created
from sharing the result.
The result to be shared can be accessed from the Results window in
the Current Session list.
Figure 7.10
Script tool result in Results
window.
Right-clicking the result opens a context menu from which you can
rerun the result, open the dialog and run the tool, copy the result as a
Python Snippet, and even edit the script.
Figure 7.11
Results window context
menu.
When the script tool has successfully created valid results, you are
ready to share the result as a geoprocessing package or
geoprocessing service. You can either store the result as a
geoprocessing package to your ArcGIS Online account, or to a local
directory.
7-13
LESSON 7
Figure 7.12
Main panel of the
Geoprocessing Package
dialog box.
Edit the script tool Item Description values before starting the
sharing process. At a minimum, complete the summary, add
tags, and provide a description for each tool parameter.
The information that you provide in the Item Description helps users
determine whether your geoprocessing package is appropriate for
their task or workflow.
Figure 7.13
Item Description panel of
the Geoprocessing
Package dialog box.
7-14
Sharing scripts
Figure 7.14
An example of the results
of unpacking the
FeatureToFeatures
geoprocessing package.
7-15
LESSON 7
While the course does not explore how to share your result as a
geoprocessing service, there are some modifications you may need to
ArcGIS Help Library:
make in your script to ensure it runs successfully as a task. The first is
A quick tour of authoring
to change your parameters for input and output data to either
and sharing
FeatureSet or RecordSet. Any hard-coded paths in your scripts must
geoprocessing services
be fully qualified, and the scratchGDB, scratchFolder, and
scratchWorkspace environments must be set. if the service is going to
create output that will be used in a map service, then the symbology
for the output data should be set to use a layer file.
7-16
Sharing scripts
Scenario
The City of Corvallis regularly holds fundraisers in Central Park. A
special parking meter rate for each event has been determined for
parking meters within a specific distance of Central Park. The city
needs to know how many meters to program with the special rate.
• The specified distance is 500 feet.
• Central Park is a feature in the Parks feature class.
• The meters to be programmed are features in the ParkingMeters
feature class.
Your task
Create a script to automate the process and share it with other GIS
users in your organization.
7-17
LESSON 7
Figure 7.15
Determining the
development process
worksheet.
Notes:
7-18
Sharing scripts
Figure 7.16
Determine the high-level
geoprocessing workflow
worksheet.
Notes:
7-19
LESSON 7
Figure 7.17
Script the pseudocode
worksheet.
Notes:
7-20
Sharing scripts
Figure 7.18
Result of selecting parking
meters that are within 500
feet of Central Park.
7-21
LESSON 7
a In PyScripter, create a new Python script and save it as MyCustomProject.py to the C:\
Student\PYTH\Sharing_scripts folder.
b Add pseudocode to your script based on the steps in your geoprocessing workflow.
Geoprocessing workflow:
• Determine Layers needed for fund raising event:
• Parks, Parking Meters
• Need Parking meters within specified distance of Central Park
• Import ArcPy module and set the current workspace
• Set the overwriteOutput environment setting to True
• Obtain script parameter values
• distance
• output feature class
• Create Feature Layers
• Create Parks feature layer for Central Park
• Create Parking Meters feature layer for selection
• Perform spatial selection
• Select all Meters that are within specified distance of Central Park
• Update Flag field to 'Y' for selected meters in the feature layer
• Copy selected meters from feature layer to new feature class
• Report selected meter count
b Set the arcpy.env environment values for the data source location.
7-22
Sharing scripts
e Call the appropriate geoprocessing tools to perform the geoprocessing operations using the
follow workflow:
1. Make feature layers for Parks and ParkingMeters (concept covered in lesson 4)
2. Perform selection by location to select all Meters that are within the specified distance of
Central Park (concept covered in lesson 4)
3. Update the Meters FLAG field (concept covered in lesson 5)
4. Copy the features from the Meters feature layer to the specified new location (Concept
covered in lesson 4)
5. Report the number of features copied to the new location (Concept covered in lesson 4)
f Save your script, check your script for syntax errors, then run the script.
Remember that parameter values are passed to the script in PyScripter through the
Command Line Parameters dialog box in the Run menu.
g Using either the ArcMap or ArcCatalog Desktop applications, verify that correct results were
created by the script.
h If necessary, make any required changes to the script and repeat the testing phase.
i Once you are satisfied with the script results, comment out the line in the script to overwrite
the output data.
j Close PyScripter.
You have determined the geoprocessing workflow, created pseudocode from the workflow,
added the pseudocode to a script as comments for documentation purposes, and written the
code from the pseudocode and workflow. Once the script was completed, you debugged the
script and ran the script to verify the correct results.
7-23
LESSON 7
Be sure the Name property for both Toolboxes and Script tools does not have a
space.
d In the Catalog window, right-click the new custom toolbox and select Add > Script.
Hint: An overview of the panels in the Add Script dialog box is provided in the Using the Add
Script wizard section in this lesson.
e For the first dialog box, provide an internal name for the script tool and an appropriate display
name for how it will be displayed in the toolbox.
f For the second dialog box, browse to the script, and then verify that the Run Python script in
process check box is checked.
If you are using the script provided for you in the C:\Student\PYTH\Sharing_scripts folder,
select MyProject.py. If you wrote your script from scratch, select MyCustomProject.py.
g For the third and final dialog box, fill in the parameters using the table above. Make sure they
are in the same order as in the script, are using the correct data type for each parameter, and
are set for input (must exist) or output (created by script) direction.
h On the script dialog, click Finish to complete the creation of the custom script tool.
7-24
Sharing scripts
This is a good time to fill out the Item Description for the tool. At a minimum, the
Tags, Summary, and Syntax > Dialog Explanation for each parameter must be filled
in before the results can be shared as a geoprocessing package.
The Item Description contents are available to anyone accessing your script tool and are placed in
the geoprocessing package when the results are shared.
By taking the time to fill out the item description, anyone who comes across your package in
ArcGIS Online, or anyone using your script tool can determine if the package is suitable and if the
tool will provide them with the results they need.
a In the ArcMap Catalog window, drag the CorvallisMeters.mxd located in the C:\Student\
PYTH\Sharing_scripts folder into the map.
b Determine if you want to run the custom tool as a dialog or if you want to run it in the Python
window. For testing purposes, specify a distance of 500.
c If you run the custom tool as a dialog, fill out the required parameters and run the tool.
7-25
LESSON 7
d If you run the custom tool in the Python window, follow these steps:
• Use arcpy.ImportToolbox to import the custom toolbox.
• Call the custom tool by its internal name along with the appended alias (i.e.,
arcpy.ProgramMeters_PYTH() ). Be sure to pass any required parameters to the tool.
Hint: You can drag the toolbox from the Catalog window into the Python window to fill out
the ImportToolbox parameter.
Once the tool completes execution, the result will be added to the table of contents.
e Verify that the results are correct and that they support the scenario.
If changes need to be made to the script, you can edit the script in PyScripter, save it, and it will
update the script in your script tool.
In this exercise, you will share the result to ArcGIS Online. Before sharing your results to ArcGIS
Online as a geoprocessing package, you need to confirm that you are connected to ArcGIS
Online.
a In the System Tray, on the lower-right side of your screen, locate the small green globe icon. If
a red X is on the globe, you are not connected to ArcGIS Online.
7-26
Sharing scripts
b If you are not connected to ArcGIS Online, choose the following option from the ArcGIS
Connection Manager properties:
d From the Results window, expand the Current Session list, right-click the most current result
for your script tool, then select Share As > Geoprocessing Package.
e In the Geoprocessing Package dialog box, choose the Upload package to my ArcGIS Online
account option. You can rename the package if you'd like.
f On the left panel, click Item Description and verify that the fields are populated.
______________________________________________________________________________
2. In the Geoprocessing Package dialog box, are changes you make in the Item Description
contents also reflected in the script tool's Item Description?
______________________________________________________________________________
g Click Analyze.
A window will display in the ArcMap application. This window contains any errors detected in the
result, the script's Item Description, the data, and the toolbox to be packaged.
7-27
LESSON 7
Most of the time, errors will be generated either for missing Item Description content,
missing syntax dialog descriptions, or for data that might have been deleted or moved.
h If you need to fix errors, you can right-click the errors, choose an option to fix the errors, then
repeat the analysis process.
i If there are no errors detected, click Share in the Geoprocessing Package dialog.
If you are not signed in to your ArcGIS Online account, the Share process will prompt you
for your Username/Password credentials.
This will package the result data, script, and toolbox into a single .gpk file. When the package is
complete, a confirmation pop-up window will display. The confirmation window will indicate the
status of the package upload and the package name.
a Open Internet Explorer and navigate to www.arcgis.com and sign in to your account.
c Click the name of your package to display its properties. Note the Description, Access and
Use Constraints, Summary and Properties are displayed.
d At this time, you may choose to Share your package with others.
7-28
Sharing scripts
g In the Download dialog box, click the Save button, then specify that you would like to save it
to the C:\Student\PYTH\Sharing_scripts folder.
h Click the Close button on the Download complete dialog box and return to ArcMap.
The package will unpack and be placed into the Shared node of the Results window. The layers in
the package will also be added to the ArcMap Table of Contents as a group layer.
Note that in the Connect to Folder dialog box, the actual folder location is C:\Users\Student\
Documents\ArcGIS. This connection is the top level folder location where all package contents are
unpacked to.
7-29
LESSON 7
If you open a blank ArcMap document using the New Map button, you may not see a connection
to Home - Documents\ArcGIS. You will need to close ArcMap and then reopen it to see the
connection as illustrated below. The Home - Documents\ArcGIS folder location is C:\Users\
Student\Documents\ArcGIS, and is the same location where you created your new connection.
l In the Catalog window, expand your new connection and click the Packages folder.
m Expand the Packages folder. Locate your package name and then explore the contents of the
v101 folder.
______________________________________________________________________________
7-30
Sharing scripts
______________________________________________________________________________
5. Does the toolbox located in the v101 folder contain your custom script tool?
______________________________________________________________________________
7-31
LESSON 7
Lesson review
______________________________________________________________________________
______________________________________________________________________________
______________________________________________________________________________
______________________________________________________________________________
______________________________________________________________________________
3. List the basic workflow for sharing GIS workflows with others.
______________________________________________________________________________
______________________________________________________________________________
______________________________________________________________________________
7-32
Sharing scripts
2. In the Geoprocessing Package dialog box, are changes you make in the Item Description
contents also reflected in the script tool's Item Description?
No, changes made in the Geoprocessing Package dialog are not saved to the tool.
5. Does the toolbox located in the v101 folder contain your custom script tool?
Yes, it is a copy of the script tool, contained in the custom toolbox, located in the
Sharing_scripts folder.
7-33
Debugging scripts and handling runtime errors
8
Debugging scripts and
handling runtime errors
Introduction
Key terms You have used several techniques to find syntax errors in your scripts.
Visually checking the code is one way to find errors, and using the
errors
Check Syntax menu item in the PyScripter main toolbar is another way
exceptions to identify errors.
try-except In this lesson, you will explore workflows for debugging your scripts
and handling any errors generated when the script is executed.
Topics covered
Learning objectives
8-1
LESSON 8
Debugging workflow
Figure 8.1
Typical workflow for
debugging scripts.
8-2
Debugging scripts and handling runtime errors
When you debug your script, make sure you do it in the right place.
Both the PyScripter application and the Python window in ArcMap are
ArcGIS Help Library:
excellent locations to debug and test your code.
Executing and debugging
Python PyScripter offers numerous resources for successfully debugging your
code, including a tool for checking code syntax, the Python
Interpreter window for print and command functionality, and the
Debugging windows.
Checking for syntax errors
Writing your script in a Python IDE, such as PyScripter or IDLE
provides you with the functionality to easily check for and correct
syntax or indentation errors.
8-3
LESSON 8
8-4
Debugging scripts and handling runtime errors
8-5
LESSON 8
Figure 8.2
Handling exceptions in
Python.
The code that you want to run in your script is placed in the try
statement. If an error occurs, an exception is raised, and the code in
the except block is then executed.
Code that you place in the except block could include print
statements for detailing the exception or fetching the geoprocessing
messages, and then reacting accordingly.
8-6
Debugging scripts and handling runtime errors
0 Informative messages
1 Warning messages
2 Error messages
8-7
LESSON 8
8-8
Debugging scripts and handling runtime errors
8-9
LESSON 8
Using Exception as e
Using the except Exception as e statement can be useful when
you need to obtain the error messages on the exception that
occurred. The except Exception as e statement will catch both
Python and Geoprocessing exceptions.
The error message for the exception that occurred is stored in e. You
can print the error messages using print e in the except statement.
Example code using a simple except Exception as e: statement:
try:
#
#
# Your code to run goes here
except Exception as e:
# print the error messages
print "An error has occurred"
print e
8-10
Debugging scripts and handling runtime errors
Using arcpy.ExecuteError
There may be times when you want to handle an exception raised by
the Geoprocessor separately from Python exceptions. The
arcpy.ExecuteError() and arcpy.ExecuteWarning() exception
classes are raised when a geoprocessing tool encounters an error or
warning. You can use the exception class in an except statement
along with a print statement to display the geoprocessing error
message or warning message.
Example code using an arcpy.ExecuteError exception class:
try:
#
#
# Your code goes here
except arcpy.ExecuteError:
# print the geoprocessing error messages
print "A geoprocessing error has occurred"
print arcpy.GetMessages(2)
except Exception as e:
# print the Python message
print "An error has occurred"
print e
If you are catching both geoprocessing exceptions and Python
exceptions in the same try-except statement, place the
except arcpy.ExecuteError statement above a standard except
statement or except Exception as e statement to guarantee that
the Geoprocessor exception is handled separately from the Python
exception.
8-11
LESSON 8
8-12
Debugging scripts and handling runtime errors
8-13
Debugging scripts and handling runtime errors
8-15
LESSON 8
c Read the script comments so that you understand the script workflow.
The script did not run, due to a syntax error. PyScripter displays a syntax error message. The Line
of code in which the error was detected is highlighted in red. Once the error message is
dismissed, the cursor is placed at the location where the syntax error was detected.
e Fix the error, then check for and fix any additional syntax errors in your script—do not run your
script yet.
To easily check for syntax errors, use the Syntax Check item under the Run menu.
Syntax Check does more than check for missing colons or improperly indented code. It will also
find variables that are being evaluated before anything is assigned to them. This is the case for
the error in line 43.
f Notice the location of the cursor on line 43 after you dismiss the error message. The cursor is
placed near the actual location of the error, but not quite on top.
1. Notice that the variables are being passed as a tuple to the str.format() function. How do
you separate each value in the tuple?
______________________________________________________________________________
g Fix the error on line 43 and check for any remaining syntax errors. Save your script.
8-16
Debugging scripts and handling runtime errors
The try-except statement block is a simple Python structure, in which the code you wish to run
is placed in the try: statement, and the code to handle the exception is placed in the except:
statement.
In the previous step, the script contained syntax errors that prevented the script from running.
Now that the syntax errors have been fixed, you are ready to run the script.
a Run the script and view the output in the Messages window.
The script failed with an ExecuteError exception number 999999, along with a message that an
expected field was not found or retrieved properly.
A good script always has code to handle exceptions and print more meaningful messages, which
provide a more positive experience to the end user.
c In the script, locate the comment # Variable assignments for GP tasks and move to the line
above the comment.
d Incorporate a try-except statement block into the script. The try: statement should include
the comment line and all lines of code below the comment.
Hint: Select all lines of code below the try: statement. Press the Tab key to indent the
selected code.
e Navigate to the bottom of the script and add an except: statement to the script. Make sure
the except: statement is at the left edge of the Editor window.
8-17
LESSON 8
Be sure the code is indented so that it will execute when Python jumps to the except:
statement.
g Check the script syntax, close PyScripter, then reopen the script.
The arcpy.GetMessages() function returns all geoprocessor messages that are generated in the
current session. These messages need to be cleared from memory, along with any variable
assignments and feature layers that might have been created. To clear them from memory, you
will close PyScripter and then reopen the script in PyScripter.
______________________________________________________________________________
______________________________________________________________________________
______________________________________________________________________________
______________________________________________________________________________
4. Based on the error messages, how might you fix the problem?
______________________________________________________________________________
______________________________________________________________________________
It appears that the error is occurring in the SelectLayerByLocation tool, but you can't be sure of
the cause. It might be a Python error or an incorrect parameter passed to the tool.
i In the next step, you will work with the Exception as e statement.
8-18
Debugging scripts and handling runtime errors
Interpreter window or added to the Geoprocessing progress dialog box, the Python window, and
the Results window.
In the previous step, a geoprocessing error was displayed by the except: statement and
indicated the error was with the arcpy.SelectLayerByLocation function. You will narrow down
the cause of the error by examining the output feature layer created by the tool.
b In the Python Interpreter window, press the Enter key to obtain a prompt.
______________________________________________________________________________
Diagnosis:
• There are no features in the RailLyr feature layer.
• The error message indicates an expected field was not found or retrieved properly when
a selection was performed on the RailLyr feature layer.
d Examine your script and locate any code that specifies fields for fc2Lyr.
f Open the properties for the Railroads feature class and click the Fields tab in the Feature Class
properties.
6. In your script, locate the variable SQLExp and compare the field it uses to the same field in
the Feature Class properties list. Do the field names match exactly?
______________________________________________________________________________
8-19
LESSON 8
g Close ArcMap, return to PyScripter, and then make the required change in the script to the
SQLExp code.
h Navigate to the bottom of the script and add the except Exception as e: statement.
k Close PyScripter, reopen the script in PyScripter, then run the script.
______________________________________________________________________________
Diagnosis:
• It appears that there might be a problem with the parameter containing the list of fields
passed to the SearchCursor. Each field name specified in the field list is a column in the
feature layer's attribute table.
o Click the Fields tab and verify that each field specified in the fields variable is correct.
______________________________________________________________________________
p In the script, make the required change to the field name, then check the script syntax.
q Close PyScripter, reopen the script in PyScripter, then run the script.
8-20
Debugging scripts and handling runtime errors
______________________________________________________________________________
Diagnosis:
• The field names parameter is no longer a problem.
• The problem now might be with the cursor or with the for-in loop code.
Your next task is to see if you can narrow down the error further. The error could be a Python error
or a geoprocessor error—as we are accessing the fields in an arcpy.da.SearchCursor.
r In the next step, you will implement the arcpy.ExecuteError exception class in your script.
d Add the following lines of code to report the geoprocessor error messages:
print "A geoprocessing error has occurred."
print arcpy.GetMessages(2)
e Press Enter a couple of times, and then add a final line to your script to indicate that the script
has completed.
f Check for syntax errors, save your script, close PyScripter, and then reopen the script in
PyScripter.
______________________________________________________________________________
To obtain more detailed information about the error, you will use the traceback and sys modules.
8-21
LESSON 8
b Navigate to the bottom of the script and add a standard except: statement just above the
final print statement.
The ArcGIS Help Library contains many Python code examples that you can use in your scripts. By
copying the example to the clipboard and then pasting it into your script, you can easily
implement the example's functionality.
e In the help page, scroll down and locate the except: statement.
f Not including the except: statement line, copy the except code into the clipboard (Ctrl+C).
g Return to PyScripter and paste the contents of the clipboard into the except: statement you
just added.
h Add the following lines of code to the bottom of the except: statement to print the Python
error messages:
print pymsg + "\n"
print msgs
i Scroll to the top of the PyScripter script window and locate the import arcpy statement.
j Add a new line under the import statement and write code to import the sys module.
Add a second line of code to import the traceback module.
k Check the script for syntax errors, close PyScripter, then reopen the script.
8-22
Debugging scripts and handling runtime errors
The messages clearly state that the error is a Python error, and the line where the error occurred is
indicated.
n Return to the script window, fix the code error, then check the script for syntax errors.
o Close PyScripter, reopen the script in PyScripter, then run the script.
p In the Python Interpreter window, scroll through the messages. The messages state that the
error is a GP error, and the line where the error occurred is indicated. In the Python Interpreter
window, continue to scroll up until you locate the PYTHON ERRORS: messages.
q The PYTHON ERRORS messages show the line of code where the error occurred.
Summary:
• The error (Error 000725) is a geoprocessing error.
• The output dataset specified for the arcpy.CopyFeatures_management function
already exists.
• Based on this information, you could add code in your script to check for the existence of
the output feature class before running the arcpy.CopyFeatures_management function,
or you could provide a warning message to the end user that the feature class already
exists.
• For testing purposes, you could set the arcpy.env.overwriteOutput = True to test
the arcpy.CopyFeatures_management function and then set the value to False before
turning the script over to end user.
r If you have the time and would like to perform one additional step, proceed to the provided
Challenge Step. Otherwise, close PyScripter.
8-23
LESSON 8
Challenge: Challenge
5 minutes
a Modify the script so that the arcpy.ExecuteError exception class catches the GP exceptions
and the standard except: statement catches the Python exceptions.
8-24
Debugging scripts and handling runtime errors
Lesson review
1. Of the error handling techniques discussed in the class, which technique returns the most
amount of detail?
______________________________________________________________________________
______________________________________________________________________________
2. Which error handlers should you use if only geoprocessing errors are to be handled?
______________________________________________________________________________
______________________________________________________________________________
______________________________________________________________________________
3. Write an except block that adds a custom error message to the Progress dialog box, the
Python window, the Results, and the Python Interpreter window in PyScripter.
______________________________________________________________________________
______________________________________________________________________________
______________________________________________________________________________
______________________________________________________________________________
______________________________________________________________________________
______________________________________________________________________________
______________________________________________________________________________
8-25
LESSON 8
4. Based on the error messages, how might you fix the problem?
• Verify that the feature layer created from the Railroads feature class was created
correctly.
• Check for an error in the arcpy.SelectLayerByLocation_management tool
parameters.
6. In your script, locate the variable SQLExp and compare the field it uses to the same field in
the Feature Class properties list. Do the field names match exactly?
No, it should be spelled "STREET_NAM".
8-26
Debugging scripts and handling runtime errors
8-27
LESSON 8
8-28
Automating map production
9
Automating map production
Introduction
Key terms Many organizations maintain a large number of map documents that
are used for a variety of reasons. The arcpy.mapping module provides
graduated colors
the ability to automate updating of map document components (such
symbology
as layers and layout elements) without the need to open the every
layer file single map document in ArcMap. This enables the scripting of map
document updates to be automated.
layout element
map document Topics covered
map layer
• Working with a map document
unique values • Listing map document contents
symbology • Managing layers
• Creating symbology
• Publishing maps
• Exporting maps and reports
Learning objectives
9-1
LESSON 9
9-2
Automating map production
Table 9.1
Term Definition
9-3
LESSON 9
Function Description
Reference The .mxd file can be referenced on disk by providing a path to the file or by
the map referencing a map document loaded into the ArcMap application with the
document "CURRENT" keyword.
Manage The ListLayoutElements function can be used with a filter to return only the elements
layout you are interested in. Layout element types returned include: DataFrame,
elements GraphicElement, LegendElement, MapSurroundElement, PictureElement, and
TextElement.
Change Functions are included to update a layer's symbology from a layer file. Additional
layer functions allow the modification of the layer's symbology for unique value symbology,
symbology graduated color symbology, and graduated symbols symbology.
Publish Functions are included to create the Service Definition Draft files, analyze the map
maps prior to the creation of the SD file, stage the SD file, and then upload the SD to the
server.
Export Map documents can be exported to all supported graphic formats. A report authored
maps and in ArcGIS Desktop can be exported to HTML, PDF, TIFF, TXT, and XLS formats.
reports
Table 9.2
9-4
Automating map production
Script tools that use the "CURRENT" keyword must be run from
ArcMap (either as a dialog or loaded into the Python window).
If the script tool is run in
ArcCatalog, there is no When using the "CURRENT" keyword in a script, be sure to disable
map document loaded the background geoprocessing option in ArcMap. When background
into the application and a processing is enabled, any script run will execute as if they were being
runtime exception will be run as a standalone script outside of the ArcGIS application. As a
thrown. result, there is no "CURRENT" map document loaded into memory.
When creating a script tool that uses the arcpy.mapping module, be
sure to confirm that the option to always run in foreground is enabled
in the script tool.
Code examples for obtaining a map document reference:
# Reference the map document on disk
mxDoc = arcpy.mapping.MapDocument(
r"C:\Student\PYTH\CityBase.mxd")
print mxDoc.title
# Reference the map document in memory
mxDoc = arcpy.mapping.MapDocument("CURRENT")
print mxDoc.filePath
9-5
LESSON 9
9-6
Automating map production
*Code samples for listing data frames, layers, and layout elements are in the C:\Student\
PYTH\Map_production\Samples folder.
9-7
LESSON 9
Managing layers
ArcGIS Help Library:
There are a number of functions in the arcpy.mapping module for
Getting started with arcpy
manipulating and working with layers in a map document.
mapping tutorial
(arcpy.mapping)
Function Description
9-8
Automating map production
There are two helper-type functions that can be used when updating
contents of a map document that is loaded in memory:
9-9
LESSON 9
9-10
Automating map production
Publishing maps
9-11
LESSON 9
9-12
Automating map production
arcpy.mapping functions
Table 9.5
arcpy.mapping function Graphics format
*Not all supported graphics formats support embedding of fonts. To ensure proper
display of fonts and color models, such as RGB and CMYK, export to the PDF format.
9-13
LESSON 9
Exporting a report
A report that has been created and saved in ArcMap can be exported
to a number of formats using the arcpy.mapping.ExportReport()
ArcGIS Help Library:
function.
ExportReport
(arcpy.mapping) The arcpy.mapping.ExportReport() function exports a formatted
tabular report created in ArcMap to a .txt, .xls, .html, .pdf, or .tif
output file. The ExportReport function uses the data from the layer or
table the report was authored from, along with the report layout file
(.rlf) information from the ArcMap reporting tools, to output the
report.
Numerous options are included in the ExportReport function to
provide a report title, a starting page number, a page range to be
exported, and an option for overriding the report definition query
extent.
Printing a map
You can write a script that prints a specific data frame or a map
document layout to a printer or file using the PrintMap() function.
If you have a printer saved with the map document, the
arcpy.mapping.PrintMap() function can print to that printer, a
specified printer name, or the default printer for your computer.
The PrintMap can be used to quickly print out your map to a printer
available to your computer, and can also print to a .prn print file.
9-14
Automating map production
9-15
LESSON 9
9-16
Automating map production
9-17
LESSON 9
9-18
Automating map production
9-19
LESSON 9
UniqueValuesSymbology method
Table 9.9
UniqueValuesSymbology Method Description
class methods
addAllValues() Updates a layer's symbology so that all values
display in the layer.
9-20
Automating map production
9-21
Automating map production
Figure 9.1
Updated map document.
9-23
LESSON 9
a Open ArcMap.
Notice the title and text elements of the map document. You will be updating the map
document's layers, symbology, layout text elements, and title.
a In PyScripter, create a new script named MyUpdateMxd.py and save it in the C:\Student\
PYTH\Map_production folder.
9-24
Automating map production
Up to this point, you have been using the standard import statement to import the arcpy module.
There are times when the default name is just too long for your preference or you would like to
make your script more readable. In any of these cases, you can use the form from-import-as.
We will use the form import arcpy.mapping as MAP to import only the mapping module
functions and classes into the script and assign the functions and classes to the name MAP.
e Use the MAP.ListDataFrames() function on the mxd object to fetch the first data frame and
assign it to a variable named df.
Hint: You can append [0] to the end of the list function to return the first item in the list
returned from the function:
MAP.ListDataFrames(mxd)[0]
9-25
LESSON 9
a In your script, use the MAP.ListLayers() function to create a layer object from the
ParkingMeters map layer, and then assign it to the variable named updateLayer.
Hint: Refer to the workbook section on Managing layers for a code example.
b Use the MAP.Layer() class to create a second layer object on the ParkingMeters.lyr file in
the Map_production folder. Assign the object to the variable named sourceLayer.
c Use the MAP.UpdateLayer() function on the updateLayer to apply only the symbology from
the sourceLayer.
d Use the MAP.Layer() class on the Schools.lyr file in the Map_production folder. Assign
the object to the variable named addLayer.
e Use the MAP.AddLayer() function to add addLayer to the map document. Take all of the
defaults.
f Using the ArcGIS Help Library, study the AddLayer function topic under the Managing
Documents and Layers book in the ArcPy > Mapping Module book.
g From your research of the AddLayer() function, answer the following questions:
1. What are the position options for adding a layer to the map document?
______________________________________________________________________________
2. If you need more precise control over the placement of the new layer than the AddLayer
function provides, which arcpy.mapping function should you use?
______________________________________________________________________________
Your final task in this step is to move the ParkingMeters layer to the top of the map document.
9-26
Automating map production
h Use the MAP.ListLayers() function to locate the newly added Schools layer in the data
frame and return the layer object to the variable named refLayer.
i Use the MAP.MoveLayer() function to move the updateLayer object to BEFORE the
refLayer object.
Be sure to check the syntax for the MoveLayer() function in the Help documentation for
specifying the correct order of the layers.
In this step, you will add code to your script to update the map document title and update the
layout 'Corvallis Meters' text element value.
a In your script, update the map document's title to 'Corvallis Meters Map'.
Hint: In the ArcGIS Help Library, search for MapDocument map document properties
(arcpy.mapping) for appropriate syntax.
b Add code to return a Python List of layout text elements using the appropriate
arcpy.mapping List function and assign to the elemList variable.
c Loop through the list of layout text elements and locate the text element that is tagged with
the name 'Corvallis Meters'. Update the element text value to
'Corvallis Parking Meters Inventory Report'.
g Run your script, and fix any errors that may occur at run time.
9-27
LESSON 9
b In the data view, verify that the ParkingMeters layer is above the Schools layer and that the
symbology for the ParkingMeters is a green orb.
d Confirm that the map title text has been updated and the text in the lower-left corner of the
layout has been updated.
e If you have time, you may proceed to the challenge step. (The challenge step should take
approximately ten minutes.)
f If you are not going to complete the optional step, you may close ArcMap without saving
changes.
9-28
Automating map production
10 minutes
a Taking the script you just created, make the script dynamic by allowing the user to select a
workspace that contains multiple map documents.
b Update the script to support looping through a list of map documents obtained from this
workspace, and then process each map document based on the code in the original script.
c After running the script successfully, create a custom script tool and test it in ArcMap or
ArcCatalog.
After creating the custom script tool, you can optionally test your script tool using the C:\
Student\PYTH\Map_production data.
9-29
LESSON 9
Lesson review
1. When modifying a map document in ArcMap, what method must be called to see the
changes?
______________________________________________________________________________
______________________________________________________________________________
2. What changes can you make to a script to automate the map document update workflow?
______________________________________________________________________________
______________________________________________________________________________
______________________________________________________________________________
3. What property must be changed in order to update the layout title text element?
______________________________________________________________________________
______________________________________________________________________________
9-30
Automating map production
2. If you need more precise control over the placement of the new layer than the AddLayer
function provides, which arcpy.mapping function should you use?
arcpy.mapping.InsertLayer()
9-31
LESSON 9
If you have time, create a script tool from your script and test in ArcMap or ArcCatalog.
9-32
Esri data license agreement
A
Esri data license agreement
IMPORTANT — READ CAREFULLY BEFORE OPENING THE SEALED MEDIA PACKAGE
ENVIRONMENTAL SYSTEMS RESEARCH INSTITUTE, INC. (ESRI), IS WILLING TO LICENSE THE
ENCLOSED ELECTRONIC VERSION OF THIS TRAINING COURSE TO YOU ONLY UPON THE
CONDITION THAT YOU ACCEPT ALL OF THE TERMS AND CONDITIONS CONTAINED IN THIS
ESRI DATA LICENSE AGREEMENT. PLEASE READ THE TERMS AND CONDITIONS CAREFULLY
BEFORE OPENING THE SEALED MEDIA PACKAGE. BY OPENING THE SEALED MEDIA
PACKAGE, YOU ARE INDICATING YOUR ACCEPTANCE OF THE ESRI DATA LICENSE
AGREEMENT. IF YOU DO NOT AGREE TO THE TERMS AND CONDITIONS AS STATED, THEN
ESRI IS UNWILLING TO LICENSE THE TRAINING COURSE TO YOU. IN SUCH EVENT, YOU
SHOULD RETURN THE MEDIA PACKAGE WITH THE SEAL UNBROKEN AND ALL OTHER
COMPONENTS (E.G., THE CD-ROM, TRAINING COURSE MATERIALS, TRAINING DATABASE,
AS APPLICABLE) TO ESRI OR ITS AUTHORIZED INSTRUCTOR FOR A REFUND. NO REFUND
WILL BE GIVEN IF THE MEDIA PACKAGE SEAL IS BROKEN OR THERE ARE ANY MISSING
COMPONENTS.
A-1
Appendix A
Permitted Uses:
• Licensee may run the setup and install one (1) copy of the Training Course onto a
permanent electronic storage device and reproduce one (1) copy of the Training Course
and/or any online documentation in hard-copy format for Licensee's own personal use
only.
• Licensee may use one (1) copy of the Training Course on a single processing unit.
• Licensee may make only one (1) copy of the original Training Course for archival purposes
during the term of this Agreement, unless the right to make additional copies is granted
to Licensee in writing by Esri.
• Licensee may use the Training Course provided by Esri for the stated purpose of
Licensee's own personal GIS training and education.
Uses Not Permitted:
• Licensee shall not sell, rent, lease, sublicense, lend, assign, time-share, or transfer, in
whole or in part, or provide unlicensed third parties access to the Training Course, any
updates, or Licensee's rights under this Agreement.
• Licensee shall not separate the component parts of the Training Course for use on more
than one (1) computer, used in conjunction with any other software package, and/or
merged and compiled into a separate database(s) for other analytical uses.
• Licensee shall not reverse engineer, decompile, or disassemble the Training Course,
except and only to the extent that such activity is expressly permitted by applicable law
notwithstanding this restriction.
• Licensee shall not make any attempt to circumvent the technological measure(s) (e.g.,
software or hardware key) that effectively controls access to the Training Course, except
and only to the extent that such activity is expressly permitted by applicable law
notwithstanding this restriction.
• Licensee shall not remove or obscure any copyright, trademark, and/or proprietary rights
notices of Esri or its licensor(s).
Term: The license granted by this Agreement shall commence upon Licensee's receipt of the
Training Course and shall continue until such time that (1) Licensee elects to discontinue use of
the Training Course and terminates this Agreement or (2) Esri terminates for Licensee's material
breach of this Agreement. The Agreement shall automatically terminate without notice if Licensee
fails to comply with any provision of this Agreement. Upon termination of this Agreement in either
instance, Licensee shall return to Esri or destroy all copies of the Training Course, and any whole
or partial copies, in any form and deliver evidence of such destruction to Esri, which evidence
shall be in a form acceptable to Esri in its sole discretion. The parties hereby agree that all
provisions that operate to protect the rights of Esri and its licensor(s) shall remain in force should
breach occur.
Limited Warranty and Disclaimer: Esri warrants that the media upon which the Training Course is
provided will be free from defects in materials and workmanship under normal use and service for
a period of ninety (90) days from the date of receipt.
EXCEPT FOR THE LIMITED WARRANTY SET FORTH ABOVE, THE TRAINING COURSE
CONTAINED THEREIN IS PROVIDED "AS-IS," WITHOUT WARRANTY OF ANY KIND, EITHER
A-2
Esri data license agreement
EXPRESS OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, AND NONINFRINGEMENT. ESRI
DOES NOT WARRANT THAT THE TRAINING COURSE WILL MEET LICENSEE'S NEEDS OR
EXPECTATIONS; THAT THE USE OF THE TRAINING COURSE WILL BE UNINTERRUPTED; OR
THAT ALL NONCONFORMITIES, DEFECTS, OR ERRORS CAN OR WILL BE CORRECTED. THE
TRAINING DATABASE HAS BEEN OBTAINED FROM SOURCES BELIEVED TO BE RELIABLE, BUT
ITS ACCURACY AND COMPLETENESS, AND THE OPINIONS BASED THEREON, ARE NOT
GUARANTEED. THE TRAINING DATABASE MAY CONTAIN SOME NONCONFORMITIES,
DEFECTS, ERRORS, AND/OR OMISSIONS. ESRI AND ITS LICENSOR(S) DO NOT WARRANT
THAT THE TRAINING DATABASE WILL MEET LICENSEE'S NEEDS OR EXPECTATIONS, THAT
THE USE OF THE TRAINING DATABASE WILL BE UNINTERRUPTED, OR THAT ALL
NONCONFORMITIES CAN OR WILL BE CORRECTED. ESRI AND ITS LICENSOR(S) ARE NOT
INVITING RELIANCE ON THIS TRAINING DATABASE, AND LICENSEE SHOULD ALWAYS VERIFY
ACTUAL DATA, WHETHER MAP, SPATIAL, RASTER, TABULAR INFORMATION, AND SO FORTH.
THE DATA CONTAINED IN THIS PACKAGE IS SUBJECT TO CHANGE WITHOUT NOTICE.
Exclusive Remedy and Limitation of Liability: During the warranty period, Licensee's exclusive
remedy and Esri's entire liability shall be the return of the license fee paid for the Training Course
upon the Licensee's deinstallation of all copies of the Training Course and providing a
Certification of Destruction in a form acceptable to Esri.
IN NO EVENT SHALL ESRI OR ITS LICENSOR(S) BE LIABLE TO LICENSEE FOR COSTS OF
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES, LOST PROFITS, LOST SALES OR
BUSINESS EXPENDITURES, INVESTMENTS, OR COMMITMENTS IN CONNECTION WITH ANY
BUSINESS, LOSS OF ANY GOODWILL, OR FOR ANY INDIRECT, SPECIAL, INCIDENTAL, AND/
OR CONSEQUENTIAL DAMAGES ARISING OUT OF THIS AGREEMENT OR USE OF THE
TRAINING COURSE, HOWEVER CAUSED, ON ANY THEORY OF LIABILITY, AND WHETHER OR
NOT ESRI OR ITS LICENSOR(S) HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
THESE LIMITATIONS SHALL APPLY NOTWITHSTANDING ANY FAILURE OF ESSENTIAL
PURPOSE OF ANY LIMITED REMEDY.
No Implied Waivers: No failure or delay by Esri or its licensor(s) in enforcing any right or remedy
under this Agreement shall be construed as a waiver of any future or other exercise of such right
or remedy by Esri or its licensor(s).
Order for Precedence: This Agreement shall take precedence over the terms and conditions of
any purchase order or other document, except as required by law or regulation.
Export Regulation: Licensee acknowledges that the Training Course and all underlying
information or technology may not be exported or re-exported into any country to which the U.S.
has embargoed goods, or to anyone on the U.S. Treasury Department's list of Specially
Designated Nationals, or to the U.S. Commerce Department's Table of Deny Orders. Licensee
shall not export the Training Course or any underlying information or technology to any facility in
violation of these or other applicable laws and regulations. Licensee represents and warrants that
it is not a national or resident of, or located in or under the control of, any country subject to such
U.S. export controls.
A-3
Appendix A
A-4
Answers to lesson review questions
B
Answers to lesson review questions
Lesson 1: Running scripts in Python (page 1-21)
2. What is ArcPy?
ArcPy provides Python access to all geoprocessing tools and a wide variety of useful
functions and classes for working with and interrogating GIS data.
3. In the Python window, how can you view help for a geoprocessing tool?
Type help, followed by an open parenthesis, followed by the tool name, followed by a
close parenthesis. The tool syntax and help documentation will display in the Python
window.
Example: help(arcpy.Buffer_analysis)
B-1
Appendix B
3. How can you obtain the name of a spatialReference for a feature class?
Describe the feature class. In the Describe object properties, access the name
property of the spatialReference object property.
B-2
Lesson 3: Automating scripts with lists
3. Write a line of code that returns a list of integer field names from a table.
Use a list comprehension:
fieldList = [field.name for field in arcpy.ListFields("Addresses")
if field.type == "Integer"]
B-3
Appendix B
1. List two geoprocessing tools that must use a feature layer to create selections.
The arcpy.SelectLayerByLocation tool and the arcpy.SelectLayerByAttribute tool must
use a feature layer to create selections.
2. What kind of schema changes can you make on a field with a FieldInfo object?
You can make the following schema changes on a field with a FieldInfo object:
• Rename the field
• Change the field visibility to HIDDEN or VISIBLE
• Set a split rule to NONE or RATIO
3. If a field is set to HIDDEN in a FieldInfo object, will the field be available in the output
feature layer?
No. When the FieldInfo object is used with the arcpy.MakeFeatureLayer tool, the field
will not be present in the output feature layer.
B-4
Lesson 5: Working with Cursors
1. When working with the da cursors, which Python statement can be used to automatically
close the cursor?
c. A with loop
2. Which token can be used with the da cursor to efficiently return the X&Y values of a point
feature?
SHAPE@XY token, SHAPE@X along with SHAPE@Y, or SHAPE@TRUECENTROID
3. Write a single line of code to return a sorted cursor of descending LAND_VALUE values
from the Corvallis Parcel feature class.
cur = [row for row in sorted(arcpy.da.SearchCursor(
"Parcel", "LAND_VALUE"), reverse = True)]
B-5
Appendix B
1. To create a Polyline or Polygon geometry object, what two objects must first be created?
A Point object and an Array object must be created before creating a Polyline or
Polygon geometry object.
2. List some geometry tokens that efficiently access Shape geometry properties.
SHAPE@XY, SHAPE@AREA, SHAPE@LENGTH, SHAPE@TRUECENTROID
3. Provide a couple of examples in which you would use a geometry object with a
geoprocessing tool.
Possible examples may include:
• Using a Polygon geometry object with the Clip tool.
• Using a Polygon geometry object with the Overlay tools.
• Creating a new buffer feature from a Polyline or Polygon geometry object or
from a Point object.
B-6
Lesson 7: Sharing scripts
3. List the basic workflow for sharing GIS workflows with others.
Author, debug and test script, create custom script tool, edit Item Description, run
script tool in ArcGIS Desktop, verify results support scenario, share results as
geoprocessing package.
B-7
Appendix B
1. Of the error handling techniques discussed in the class, which technique returns the most
amount of detail?
The traceback module used in conjunction with the sys module
2. Which error handlers should you use if only geoprocessing errors are to be handled?
The arcpy.ExecuteError and arcpy.ExecuteWarning handlers will raise an exception
only if a geoprocessing tool error or warning is encountered.
3. Write an except block that adds a custom error message to the Progress dialog box, the
Python window, the Results, and the Python Interpreter window in PyScripter.
except:
msg = "My custom error message"
arcpy.AddError(msg)
print msg
B-8
Lesson 9: Automating map production
1. When modifying a map document in ArcMap, what method must be called to see the
changes?
arcpy.RefreshActiveView() or arcpy.RefreshTOC()
2. What changes can you make to a script to automate the map document update workflow?
• Use arcpy.ListFiles() function to return a Python List of mxds and iterate
through the list.
• Replace all hard-coded variables with arcpy.GetParameterAsText().
• Add script to custom toolbox, then run the custom tool in Batch mode.
3. What property must be changed in order to update the layout title text element?
The change must be made to the map document's title property—not to the layout
text element.
B-9