Python ArcGIS Lesson7

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

Transcript of Python ArcGIS Lesson7

Page 1: Python ArcGIS Lesson7

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 UniversityWith Material from ESRI

Page 2: Python ArcGIS Lesson7

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.

Page 3: Python ArcGIS Lesson7

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

Page 4: Python ArcGIS Lesson7

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.

Page 5: Python ArcGIS Lesson7

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.

Page 6: Python ArcGIS Lesson7

Example Coding: Error Messages # Check the current workspace for a dataset specified by userif 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")

Page 7: Python ArcGIS Lesson7

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.

Page 8: Python ArcGIS Lesson7

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.

Page 9: Python ArcGIS Lesson7

Example Code: Try…Except statement# Set variables for the argumentsinput = sys.argv[1]output = sys.argv[2]

# Set the workspacegp.workspace = (r"C:\john\Lesson7_results")

# Run buffer analysis within try...except statementtry:

gp.buffer_analysis (input, output, 100)except:

print "An Error occurred with Buffer_analysis..."

Page 10: Python ArcGIS Lesson7

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.

Page 11: Python ArcGIS Lesson7

Example Code: Using GetMessage() Method

# Set variables for the argumentsinput = sys.argv[1]output = sys.argv[2]

# Set the workspacegp.workspace = (r"C:\john\Lesson7_results")

# Run buffer analysis within try...except statementtry:

gp.buffer_analysis (input, output, 100)except:

print gp.GetMessage() # PythonWin Error Messagegp.AddMessage (gp.GetMessage()) # ArcToolbox Error Message

01

2

3

45

Page 12: Python ArcGIS Lesson7

Example Code: Parsing GetMessage() Method

# Set variables for the argumentsinput = sys.argv[1]output = sys.argv[2]

# Set the workspacegp.workspace = (r"C:\john\Lesson7_results")

# Run buffer analysis within try...except statementtry:

gp.buffer_analysis (input, output, 100)except:

print gp.GetMessage(3) # PythonWin Error Messagegp.AddError (gp.GetMessage(3)) # ArcToolbox Error Message

Page 13: Python ArcGIS Lesson7

Example Code: GetMessages(severity)

# Run buffer analysis within try...except statementtry:

gp.buffer_analysis (input, output, 100)except:

print gp.GetMessages(2) # PythonWin Error Messagegp.AddMessage (gp.GetMessages(2)) # ArcToolbox ‘Error’ Message

• Used to filter messages– To return ‘messages’ only, use 0– To return ‘errors’ only, use 2– To return ‘warnings’ only, use 1

Page 14: Python ArcGIS Lesson7

Example Code: Licensing Methods

# Check if extension is available, if not notify userif 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”

• 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

Page 15: Python ArcGIS Lesson7

Example Code: Product Methods

# Check if ArcInfo version of ArcGIS is availableif 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”

• 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

Page 16: Python ArcGIS Lesson7

Lesson 7b: Value Tables

• Some ArcToolbox tools require multivalue input– Examples: Intersect, Union, Merge, Append, etc.

• Value Table objects can be used to ‘hold’ multivalueinput parameters.

Page 17: Python ArcGIS Lesson7

Value Table Objects

• Accessed with CreateObject method

• Value Table object has:

– Read-only properties

– Methods to • add/remove rows

• get/set values

Page 18: Python ArcGIS Lesson7

Example Code: Value Table Objects

# Create the empty value tablevTab = 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 fcwhile fc:

vTab.Addrow(fc)fc = fcList.Next()

# Use the Merge tool to create an output FC from the merged FCsgp.Merge_management(vTab, “mrg_out.shp”, "")

Page 19: Python ArcGIS Lesson7

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 .tbxextension

• Give it a name starting with ‘Z’ so that is goes to the bottom.

Page 20: Python ArcGIS Lesson7

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:

Page 21: Python ArcGIS Lesson7

• 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.

Page 22: Python ArcGIS Lesson7

• 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.

Page 23: Python ArcGIS Lesson7

• 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

Page 24: Python ArcGIS Lesson7

• 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.

Page 25: Python ArcGIS Lesson7

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

2

3

Page 26: Python ArcGIS Lesson7

Documentation Editor:

Page 27: Python ArcGIS Lesson7

Documentation Editor:

Paragraph

BulletsHyperlink

Image

SubsectionIndent

Delete

Page 28: Python ArcGIS Lesson7

Documentation Editor:

Page 29: Python ArcGIS Lesson7

Documentation Editor:

Page 30: Python ArcGIS Lesson7

Documentation Editor:

Page 31: Python ArcGIS Lesson7

Accessing HelpDocumentation:

Page 32: Python ArcGIS Lesson7

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

Page 33: Python ArcGIS Lesson7

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.

Page 34: Python ArcGIS Lesson7

• 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.exefile.

• Click OK to save what you’ve done.

Page 35: Python ArcGIS Lesson7

• 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.’

Page 36: Python ArcGIS Lesson7

Example of an AML with arguments:&args grd outgrd&if [null %outgrd%] &then&return Usage: TRMIM <elevation grid> <outgrid>

/* start Gridgrid

/********************************************************************&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)...

Page 37: Python ArcGIS Lesson7

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 havearguments 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,ycoordinates; 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 forthe 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.