Using tools in Python

Every geoprocessing tool has a fixed set of parameters that provide the tool with the information it needs for execution. Tools usually have input parameters that define the dataset or datasets that are typically used to generate new output data. Parameters have several important properties:

Name

Each tool parameter has a unique name.

Type

The type of data expected, such as feature class, integer, string, and raster.

Direction

The parameter defines either input or output values.

Required

Either a value must be provided for a parameter or it is optional.

When a tool is used in a script, its parameter values must be correctly set so it can execute when the script is run. The documentation of each tool clearly defines its parameters and properties. Once a valid set of parameter values is provided, the tool is ready to be executed.

Parameters are specified as either strings or objects. Strings are simply text that uniquely identifies a parameter value, such as a path to a dataset or a keyword.

Most tool parameters can be specified as a simple string. For some parameters, such as a spatial reference, you can use an object instead of a string. In the following code example, input and output parameters are defined for the Buffer tool. Note that the tool name is always appended with its toolbox alias. In the example, two string variables are used to define the input and output parameters to make the call to the tool easier to read.

import arcpy

roads = "c:/St_Johns/data.gdb/roads"
output = "c:/St_Johns/data.gdb/roads_Buffer"

# Run Buffer using the variables set above and pass the remaining parameters
#   in as strings
#
arcpy.Buffer_analysis(roads, output, "distance", "FULL", "ROUND", "NONE")

In the following code example, the CreateFeatureClass tool is executed using a spatial reference object for its optional Coordinate System parameter. The spatial reference object is created using the SpatialReference class, and its information is loaded from a projection file.

import arcpy

inputWorkspace = "c:/temp"
outputName =  "rivers.shp"

# Create a spatial reference object
#
spatialRef = arcpy.SpatialReference()

# Use a projection file to define the spatial reference's properties
#
spatialRef.createFromFile("c:/program files/arcgis/Desktop10.0/Coordinate Systems/" + \
                          "Projected Coordinate Systems/Continental/North America/North America Equidistant Conic.prj")

# Run CreateFeatureclass using the spatial reference object
#
arcpy.CreateFeatureclass_management(inputWorkspace, outputName, 
                                    "POLYLINE", "", "", "", spatialRef)

Tool organization

Geoprocessing tools are organized in two different ways. All tools are available as functions on ArcPy but are also available in modules matching the toolbox alias name. Although most of the examples in the help show tools organized as functions available from ArcPy, both approaches are equally valid. Which approach you use will come down to a matter of personal preference and coding habits. In the following example, the GetCount tool is shown using both approaches.

import arcpy

inFeatures = "c:/temp/rivers.shp"

# Tools can be accessed as functions on the arcpy module, and
#  from modules matching the toolbox name.
#
arcpy.GetCount_management(inFeatures)
arcpy.management.GetCount(inFeatures)

When using tools in modules, sometimes you may want to draw attention to how a module is identified to make your script more readable. In this case, you can use the form from - import - as.

# Clean up street centerlines that were digitized without having set
#  proper snapping environments
#
import arcpy
from arcpy import edit as EDIT
from arcpy import management as DM

streets = "c:/data/streets.gdb/majorrds"
streetsCopy = "c:/output/Output.gdb/streetsBackup"

DM.CopyFeatures(streets, streetsBackup)
EDIT.TrimLine(streets, "10 Feet", "KEEP_SHORT")
EDIT.ExtendLine(streets, "15 Feet", "EXTENSION")
LicenseLicense:

Spatial Analyst tools are handled differently to accommodate Map Algebra and are available only in the arcpy.sa module and not as functions on ArcPy.

Getting results from a tool

ArcPy returns the output values of a tool when it is executed as a Result object. The advantage of a result object is that you can maintain information about the execution of tools, including messages, parameters, and output. These results can be maintained even after several other tools have been run.

The following examples show how to get the output from a result object following the execution of a geoprocessing tool.

import arcpy

arcpy.env.workspace = "D:/St_Johns/data.gdb"

# Geoprocessing tools return a result object of the derived 
#   output dataset. 
#
result = arcpy.CopyFeatures_management("roads", "urban_roads")

# A print statement will display the string 
#   representation of the output.
#
print result 

# To get the output value, the result object has a getOutput method
#
resultValue = result.getOutput(0)

 

NoteNote:

The result object's getOutput method returns a Unicode string from result objects that have output values. This is an important consideration when running a tool such as GetCount, which provides a count of records in a table, or CalculateDefaultClusterTolerance, which provides a cluster tolerance value. To convert the value to the expected type, it will have to be converted from a unicode string using built-in Python functions such as int() or float().

import arcpy
from arcpy import env
import types

env.workspace = "c:/St_Johns/data.gdb"

# Many geoprocessing tools return a result object of the derived 
#   output dataset. A print statement will display the string 
#   representation of the output.
#
result = arcpy.GetCount_management("roads")
resultValue = result.getOutput(0)

# The result object's getOutput method returns values as a 
#   unicode string.  To convert to a different Python type, use 
#   built-in Python functions: str(), int(), long(), float()
#
count = int(resultValue)
print count
print types.TypeType(count) 
Result properties and methods

Properties and methods

Explanation

inputCount

Returns the number of inputs.

outputCount

Returns the number of outputs.

messageCount

Returns the number of messages.

maxSeverity

Returns the maximum severity. The returned severity can be 0 (no errors/warnings raised), 1 (warnings raised), or 2 (errors raised).

resultID

Returns the unique result ID. If the tool is not a geoprocessing service, the resultID will be "".

status

Returns the status of the job on the server.

  • 0—New
  • 1—Submitted
  • 2—Waiting
  • 3—Executing
  • 4—Succeeded
  • 5—Failed
  • 6—Timed Out
  • 7—Canceling
  • 8—Canceled
  • 9—Deleting
  • 10—Deleted

cancel()

Cancels the job on the server.

getInput(index)

Returns a given input. If a record set or raster data object, a RecordSet or RasterData object is returned.

getMapImageURL(ParameterList, Height, Width, Resolution)

Get map service image for a given output.

getMessage(index)

Returns a specific message.

getMessages(severity)

The type of messages to be returned. 0=message, 1=warning, 2=error. Not specifying a value returns all message types.

getOutput(index)

Returns a given output. If a record set or raster data object, a RecordSet or RasterData object is returned.

getSeverity(index)

Returns the severity of a specific message.

Result properties and methods

Getting results from a server tool

Like other geoprocessing tools, geoprocessing server tools have a fixed set of parameters that provide the tool with the information it needs for execution. When using asynchronous server tools in a script, the output can be retrieved by the result's getOutput method.

TipTip:

The IsSynchronous function can be used to determine whether a tool is run synchronously or asynchronously. When a tool is synchronous, the results are automatically returned, but no other action may be taken until the tool has completed.

In the following example, the GetParameterValue function is used to get a FeatureSet object from a server tool. This FeatureSet object contains the schema of the tool's input parameter. The FeatureSet object is then loaded with a feature class, and the server tool is executed on the server. The script ends by using the result object's getOutput method to get the tool output's, which is then saved locally by using the FeatureSet's save method.

import arcpy
import time

# Add a toolbox from a server
#
arcpy.ImportToolbox("http://flame7/arcgis/services;GP/BufferByVal", "mytools")

# Use GetParameterValue to get a featureset object with the default 
#   schema of the first parameter of the tool 'bufferpoints'
#
inFeatureSet = arcpy.GetParameterValue("bufferpoints", 0)

# Load a shapefile into the featureset
#
inFeatureSet.load("c:/base/roads.shp")

# Run a server tool named BufferPoints with featureset created above
#
result = arcpy.BufferPoints_mytools(inFeatureSet, "5 feet")

# Check the status of the result object every 0.2 seconds until it has a value 
#    of 4 (succeeded) or greater
#
while result.status < 4:
    time.sleep(0.2)

# Get the output FeatureSet back from the server and save to a local geodatabase
#
outFeatSet = result.getOutput(0)
outFeatSet.save("c:/temp/base.gdb/towers_buffer")

Getting a raster result from a server tool

Raster results are returned as Tagged Image File Format (TIFF). By default, when using getOutput, the TIFF is written to your system's TEMP folder. To control the location of the TIFF, set the scratchWorkspace environment to a folder.

import arcpy 
import time

# Set the scratchworkspace to a folder.
#
arcpy.env.scratchWorkspace = "c:/temp/rasteroutput"

# Add a toolbox from a server
#
arcpy.ImportToolbox("http://flame7/arcgis/services;SlopeByVal", "mytools")

dem = "c:/dems/k_ne_g"

# Run a server tool named RunSlope
#
result = arcpy.RunSlope_mytools(dem)

# Check the status of the result object every 0.2 seconds until it has a value 
#    of 4 (succeeded) or greater
#
while result.status < 4:
    print result.status
    time.sleep(0.2)

# Raster output will be written to the scratchworkspace    
#
outTIFF = result.getOutput(0)

Getting a map image

Geoprocessing services can have a result map service to create a digital map image of task results. Digital maps contain visual representations of geographic datasets that communicate information. Digital maps are transported across the Web as images (such as a .jpeg). A map image, byte for byte, contains far more human-interpretable information than raw features in a feature class. Map images are also manageable—they are easily compressed, they can be tiled into manageable chunks, and there are established methods for transporting and viewing them across the Web.

Map images are created by an ArcGIS Server map service and are the result of publishing an ArcMap document (.mxd). Because of the characteristics of a map image, you may want to create one for the results of your geoprocessing task and transport the image across the Web rather than transporting the result dataset or datasets. Geoprocessing services can have a result map service used by ArcGIS Server to create map images of your output data.

import arcpy
import time
import urllib

# Add a toolbox from a server
#
arcpy.ImportToolbox("http://flame7/arcgis/services;GP/BufferByVal", "mytools")

# Use GetParameterValue to get a featureset object with the default schema of the 
#   first parameter of the tool 'bufferpoints'
#
inFeatureSet = arcpy.GetParameterValue("bufferpoints", 0)

# Load a shapefile into the featureset
#
inFeatureSet.load("c:/base/roads.shp")

# Run a server tool named BufferPoints with featureset created above
#
result = arcpy.BufferPoints_mytools(inFeatureSet, "5 feet")

# Check the status of the result object every 0.2 seconds until it has a value 
#    of 4 (succeeded) or greater
#
while result.status < 4:
    time.sleep(0.2)
    print result.status

# Return a map service
#
mapimage = result.getMapImageURL(0)

# Use Python's urllib module's urlretrieve method to copy the image locally
#
urllib.urlretrieve(mapimage, "c:/base/road_buffer.jpg")

Related Topics


12/15/2011