Você está na página 1de 37

Lesson 7: Error Checking, Value

Tables, Documenting Scripts in


ArcToolbox, and Running AMLs from
ArcToolbox
Basic Programming in ArcGIS with Python
Workshop
RS/GIS Lab, Utah State University
With Material from ESRI
Learning Objectives:
• Learn about error checking and handeling in both
PythonWin and ArcToolobox.
• Learn how and when to use Value Tables.
• Learn about creating documentation for tools in
ArcToolbox.
• Learn about how to transport a script within an
toolbox.
• Learn about how to run an AML from ArcToolbox.
Lesson 7a: Error Checking and Handeling

• Why Check for Errors?


– Helps you see problems as you’re writing code.
– Errors can occur when the user interacts with the script.
– Make the error messages more meaningful.
• Types of error checking:
– Check for specific errors
– Check for non-specific errors
– License & product checking
Checking for Errors:
• Examples of specific errors:
– Input data does not exists
– Output data does not exist
– User entered the wrong type of data
– More…?
• Testing for specific errors:
– If-elif-else statement
– Use gp.Exists Method
• Works for all types of data including text files
– Use gp.Describe Method
• Test type of data (raster, shapefile, geodatabase), spatial
reference, cell size, etc.
Error Messages in ArcToolbox versus PythonWin:

• Python print statement sends message to Interactive


Window
• Messaging Methods send messages to the progress
dialog box (ArcToolbox) and Command Line window.
Example Coding: Error Messages
# Check the current workspace for a dataset specified by user
if gp.Exists(dataset):
gp.AddMessage("This is a 'message: "+os.path.basename(dataset)+" exists")
gp.AddWarning("This is a 'warning: "+os.path.basename(dataset)+" exists")
gp.AddError("This is an 'error', "+os.path.basename(dataset)+" exists")
print "THE DATASET "+os.path.basename(dataset)+ " EXISTS"
else:
print “THE DATASET "+os.path.basename(dataset)+ “DOES NOT EXIST")
ArcToolbox: Tool’s dialog incorporates some error
checking
• If data type is assigned to arguments when adding the
script to the tool.
• Exists method not necessary to test for data.
Checking for Errors…Continued
• Checking for all errors:
– When you can’t anticipate every possible error.
– When you’re debugging your code.

• Try…except statement:

try:
# Write the code here (i.e. the steps in the code that may result
# in errors). Some people put all their code here.
except:
# If the code in the try block creates and error, Python will not
# handle the error, and will instead skip to the except block.
# Here, in the except, block you can write code to determine how
# to handle the error.
Example Code: Try…Except statement
# Set variables for the arguments
input = sys.argv[1]
output = sys.argv[2]

# Set the workspace


gp.workspace = (r"C:\john\Lesson7_results")

# Run buffer analysis within try...except statement


try:
gp.buffer_analysis (input, output, 100)
except:
print "An Error occurred with Buffer_analysis..."
Using the GetMessage() and GetMessages() Methods
• GetMessage(index)
– Returns a string of all messages from the last geoprocessing
tool executed
– Is indexed—so it can be parsed to display only certain
messages.
• GetMessages(severity)
– Specifying severity level, filters based on error severity.
• Both deal with geoprocessing tools, NOT with Python
errors.
Example Code: Using GetMessage() Method
# Set variables for the arguments
input = sys.argv[1]
output = sys.argv[2]

# Set the workspace


gp.workspace = (r"C:\john\Lesson7_results")

# Run buffer analysis within try...except statement


try:
gp.buffer_analysis (input, output, 100)
except:
print gp.GetMessage() # PythonWin Error Message
gp.AddMessage (gp.GetMessage()) # ArcToolbox Error Message

0
1

4
5
Example Code: Parsing GetMessage() Method
# Set variables for the arguments
input = sys.argv[1]
output = sys.argv[2]

# Set the workspace


gp.workspace = (r"C:\john\Lesson7_results")

# Run buffer analysis within try...except statement


try:
gp.buffer_analysis (input, output, 100)
except:
print gp.GetMessage(3) # PythonWin Error Message
gp.AddError (gp.GetMessage(3)) # ArcToolbox Error Message
Example Code: GetMessages(severity)
• Used to filter messages
– To return ‘messages’ only, use 0
– To return ‘errors’ only, use 2
– To return ‘warnings’ only, use 1
# Run buffer analysis within try...except statement
try:
gp.buffer_analysis (input, output, 100)
except:
print gp.GetMessages(2) # PythonWin Error Message
gp.AddMessage (gp.GetMessages(2)) # ArcToolbox ‘Error’ Message
Example Code: Licensing Methods
• Check out the extension if using an extension tool
– gp.CheckExtension()–to see if a license is available to be checked out
– gp.CheckOutExtension()—to retrieve a license from the license manager
– gp.CheckInExtension()—to return a license to the license manager

# Check if extension is available, if not notify user


if gp.CheckExtension (“spatial”):
try:
gp.ViewShed_sa (elvGrd, "xxsel"+i+".shp", "xxvshd"+i)
except:
print gp.GetMessages(2)
else:
print “The spatial analyst extension is not available”
gp.AddMesssage “The spatial analyst extension is not available”
Example Code: Product Methods
• Check out the extension if using an extension tool
– gp.CheckProduct()–to see which desktop licenses are available
– gp.ProductInfo()—to report the current desktop license
– gp.SetProduct()—to define the desktop license

# Check if ArcInfo version of ArcGIS is available


if gp.CheckProduct (“ArcInfo”)== “Available”:
try:
gp.PolygonToLine_management (“HmRange1990.shp”, “HmRngLine.shp”
except:
print gp.GetMessages(2)
else:
print “You need an ArcInfo license to run this script”
gp.AddMesssage “You need an ArcInfo license to run this script”
Lesson 7b: Value Tables

• Some ArcToolbox tools require multivalue input


– Examples: Intersect, Union, Merge, Append, etc.
• Value Table objects can be used to ‘hold’ multivalue
input parameters.
Value Table Objects

• Accessed with CreateObject method


• Value Table object has:
– Read-only properties
– Methods to
• add/remove rows
• get/set values
Example Code: Value Table Objects

# Create the empty value table


vTab = gp.CreateObject("ValueTable")
# Get a list of of all the FCs that begin with 'xxdis'
fcList = gp.ListFeatureClasses("xxdis*")
fc = fcList.Next()
# Add a row to the vTab for each fc
while fc:
vTab.Addrow(fc)
fc = fcList.Next()
# Use the Merge tool to create an output FC from the merged FCs
gp.Merge_management(vTab, “mrg_out.shp”, "")
Lesson 7c: Adding Scripts as Tools in ArcToolbox

• Advisable to
create the new
Toolbox in
ArcCatalog, within
the folder you wish
to put the toolbox
(e.g. Lesson7).
• The toolbox is a
file with a .tbx
extension
• Give it a name
starting with ‘Z’ so
that is goes to the
bottom.
Review: Adding Scripts as Tools in ArcToolbox

• Once the toolbox is created, you


can add tools to it.
• ‘Adding’ a script starts a Wizard
that walks you through populating
4 sets of properties (tabs) for the
script:
• General:
– Name: must be unique, no
spaces, used in command
line and scripts
– Label: need not be unique.
Used for tool’s display
name.
– Description: appears in the
Help Panel.
– Stylesheet: controls the
dialog’s appearance.
– Relative Paths: When set
path name between the
.tbx file and the .py file is
relative.. Very useful when
transporting the tool.
• Source:
– Path to the script file that
will be executed from the
tool
– Can be Python, VBScript,
Jscript, AML, and EXE
– Points to the script, so if
the script gets updated,
the tool gets updated.
– Usually not necessary
unless running system
commands—running an
AML is running a system
command.
• Parameters:
– Display Name: label for the
parameter in the dialog
– Data Type: type of dataset
– Type: defines whether
parameter is required or
optional.
– Direction: whether parameter
is input or output
– Multi-value: Parameter
handles multiple values.
– Default: default value for the
parameter.
– Environment: make
parameter display current
env. setting.
– Domain: Limits acceptable
values (range & coded)
– Dependency: makes one
parameter dependent on
another parameter
• Help:
– Help documentation that
can be attached to the
tool.
– A CHM (compiled help) file
is a compiled HTML
document that is created
outside ArcGIS.
– The CHM file will take
precedence over the Help
Documentation stored with
the toolbox.
Documentation Editor: Adding Documentation to Tools

• Two ways to start editor:


– Right-click the tool and click ‘Edit Documentation.’
– Click the tool in the Catalog tree (1) and then click on
Metadata tab (2), then click on ‘Edit Metadata’ button (3).

1
Documentation Editor:
Documentation Editor:

Paragraph

Bullets
Hyperlink
Image
Subsection
Indent

Delete
Documentation Editor:
Documentation Editor:
Documentation Editor:
Accessing Help
Documentation:
Lesson 7d: Transporting Toolboxes with scripts

• Must transport both the toolbox file (.tbx) and


the Python script (.py).
• If toolbox is saved with relative paths, the tool
should work as long as relative paths are
maintained.
• If relative paths are not maintained, re-
establish the path to the .py script under
‘Source’ tab of tool’s properties
Lesson 7e: Making AMLs run as tools in ArcToolbox

• AMLs can be added as tools to a toolbox much


like a Python script.
• You must have Arc/INFO version of ArcGIS.
• Must set up Windows to know that it needs to
run Arc for files with an .aml extension.
• AMLs can have arguments, which can be set
as Parameters in Arctoolbox in the same way
Python scripts have arguments.
• In an Explore browser, go to Tools,
choose Folder Options.
• Click on the File Types tab. Wait until if
finds all the Registered file types. Type
‘a’ to move to the extensions starting
with ‘a’.
• Find ‘AML’ file type, then click on
Avanced Button. For Actions, you
should see ‘edit’ and ‘open.’
• Click on ‘open’ then click the Edit
button.
• Edit the ‘open’ Action so that it looks as
below, where the path to arc.exe is the
path on your computer (if you don’t
know it, use Windows search to find it).
• So in this example, the arc.exe file is at:
C:\arcgis\arcexe9x\bin\. The remaining
part “&run” %0 %* is required
regardless of the path to your arc.exe
file.
• Click OK to save what you’ve done.
• You will also need to set the registry so
that Windows knows was program to
use when you what to edit an .aml file.
• You do this in the same way, except for
the Action, choose ‘edit’ and then click
on the Edit button.
• A complete path to the program
executable to edit files does not seem
necessary, so when you set the
application to perform the ‘edit’ action.
• Here, I’m saying I want to use Notepad
for my text editor. When done, click
OK, then click OK, then click Close for
‘Folder Options.’
Example of an AML with arguments:
&args grd outgrd
&if [null %outgrd%] &then
&return Usage: TRMIM <elevation grid> <outgrid>

/* start Grid
grid

/********************************************************************
&routine calc_slope
/********************************************************************
&type Calculating degree slope as integer...
xxslp_int = int(slope(%grd%, degree))
&type Reclassifying final slope factor grid...
xxslp_fact = reclass(xxslp_int, %textfilepath%/slp_reclass.txt, nodata)
&type ****************************
&type Done with slope factor grid!
&type ****************************
&return

/********************************************************************
&routine calc_aspect
/********************************************************************
&type Calculating aspect as integer...
xxasp_int = int(aspect(%grd%))
&type Reclassifying aspect...
xxasp_rcl = reclass(xxasp_int, %textfilepath%/asp_reclass.txt, nodata)
.
.
.
Assignment for Lesson 7
• There are two options for this week’s assignment.
• Option 1: Write a script that can be used to determine the length
of hiking trails that are within the viewshed of each nestsite in a
dataset. The script should have error checking, and should have
arguments for the required datasets. Turn in the script as a tool in
a toolbox.
• Option 2: Write a script that can be used to read-in a list of x,y
coordinates; from that list of x,y coordinates, create a new
shapefile with square polygons centered on the x,y coordinate
pair. The size of the polygons should be 200 m x 200 m. The
script should have error checking, and should have arguments for
the required datasets. Turn in the script as a tool in a toolbox.
• You are free to do both options, but are required to do only one.

Você também pode gostar