Use tools in Python

A geoprocessing tool has a fixed set of parameters that provide the tool with the information required for implementation. 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:

  • Each parameter expects a specific data type or data types, such as feature class, integer, string, or raster.
  • A parameter expects either an input or output value.
  • A parameter either requires a value or is optional.
  • Each tool parameter has a unique name.

When a tool is used in Python, its parameter values must be correctly set so it can be run successfully. Once a valid set of parameter values is provided, the tool is ready to be run. Parameters are specified as either strings or objects.

Strings are 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.analysis.Buffer(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 run 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.management.CreateFeatureclass(
    in_workspace, output_name, spatial_reference=spatial_ref)

Most geoprocessing tools include both required and optional arguments. Oftentimes there are cases in which 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.management.AddField("schools", "school_id", "LONG", "", "", "", "", "NON_NULLABLE")

A better alternative: skipping optional arguments using keyword arguments.

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

Tool output

ArcPy returns the output values of a tool when it is run and returned as a Result object. A Result object maintains information about a tool operation after it has completed. This includes messages, parameters, and outputs. Functions such as arcpy.GetMessages provide information solely from the preceding tool. However, you can maintain a Result object even after running other tools.

The following examples show how to get the output from a result object after a geoprocessing tool has run.

import arcpy

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

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

# Using print function 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]

You can index the result object using either getOutput or Python indexing. The index can be the integer index of the parameter, or the parameter's name. When indexing the result object or using its getOutput method, the return value is a 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 to the expected type, built-in Python functions, such as int or float, can be used.

Hinweis:

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.management.GetCount("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(), float()
count = int(result_value)
print(count)
print(type(count))

When creating intermediate output, omit a tool's output argument. The tool will create a unique path and name for the output. Set the output to a value of "#" or None, or if the output would be the last argument used, skip it entirely.

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

result1 = arcpy.management.CopyFeatures("roads", "#")
result2 = arcpy.management.CopyFeatures("roads", "")
result3 = arcpy.management.CopyFeatures("roads")

Tool organization

ArcPy provides access to geoprocessing tools in two ways:

  • As functions directly from arcpy
  • As functions within toolbox modules

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 uses both approaches.

import arcpy

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

# Tools can be accessed from modules matching the toolbox name
arcpy.management.GetCount(in_features)

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

When using tools from a module, you may sometimes want to draw attention to the module. In this case, use the import 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")
Lizenz:

Spatial Analyst and Image Analyst tools are organized differently to accommodate Map Algebra, and they are available only in the arcpy.sa and arcpy.ia modules and not as functions on ArcPy.