Using tools in Python

A 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:

When a tool is used in Python, its parameter values must be correctly set so it can execute when the script is run. 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. In the following code example, input and output parameters are defined for the Buffer tool. Note that the tool name is 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:/base/data.gdb/roads"
output = "c:/base/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")

For some parameters, such as a spatial reference, an object can also be specified. In the following code example, the Create Feature Class tool is executed using a SpatialReference object for its optional Coordinate System parameter.

import arcpy

in_workspace = "c:/temp"
output_name = "rivers.shp"

# Create a spatial reference object
spatial_ref = arcpy.SpatialReference('North America Equidistant Conic')

# Run CreateFeatureclass using the spatial reference object
arcpy.CreateFeatureclass_management(
    in_workspace, output_name, spatial_reference=spatial_ref)

Most geoprocessing tools include both required and optional arguments. Oftentimes there are cases where there are many optional arguments that don't need to be specified. There are a couple of strategies for dealing with these unused arguments. One is to keep all optional arguments in order, and reference those you don't need as either an empty string "", a pound sign "#" or with a None type. A second strategy is to use keyword arguments and use the argument name to assign a value. Using keyword arguments allows you to skip unused optional arguments or specify them in different orders.

Skipping optional arguments using empty strings.

import arcpy
arcpy.AddField_management("schools", "school_id", "LONG", "", "", "", "", "NON_NULLABLE")

A better alternative; skipping optional arguments using keyword arguments.

import arcpy
arcpy.AddField_management("schools", "school_id", "LONG", field_is_nullable="NON_NULLABLE")

Tool output

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 = "c:/city/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 

# A result object can be indexed to get the output value.
# Note: a result object also has a getOutput() method that 
# can be used for the same purpose.
result_value = result[0]

When indexing the result object or using its getOutput() method, the return value is a Unicode string. This is an important consideration when running a tool with a derived output parameter such as Get Count, which provides a count of records in a table, or Calculate Default Cluster Tolerance, which provides a cluster tolerance value. To convert the unicode string to the expected type, built-in Python functions such as int() or float() can be used.

NoteNote:

A derived parameter requires no interaction from the user and does not show up on the tool dialog box or as an argument to the tool in Python. Derived types are always output parameters.

import arcpy
import types

arcpy.env.workspace = "c:/base/data.gdb"

# Many geoprocessing tools return a result object of the derived 
# output dataset.
result = arcpy.GetCount_management("roads")
result_value = result[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(result_value)
print count
print types.TypeType(count)

If creating output that is just an intermediate stage in a larger workflow, the output argument can be omitted to allow the tool to create a unique path and name for the output. This can be accomplished by setting the output either to "#" or None, or if the output would be the last argument used, skip it entirely. In each case, the returned value is the full path to the new datasource.

import arcpy
arcpy.env.workspace = "c:/city/data.gdb"

result = arcpy.CopyFeatures_management("roads", "#")
result = arcpy.CopyFeatures_management("roads", "")
result = arcpy.CopyFeatures_management("roads")

Tool organization in ArcPy

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 Get Count tool is shown using both approaches.

import arcpy

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

# Tools can be accessed as functions on the arcpy module
arcpy.GetCount_management(in_features)

# Or from modules matching the toolbox name
arcpy.management.GetCount(in_features)

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"
streets_copy = "c:/output/Output.gdb/streetsBackup"

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

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

Related Topics

4/12/2013