A quick tour of ArcPy
ArcPy is a site package that builds on (and is a successor to) the successful arcgisscripting module. Its goal is to create the cornerstone for a useful and productive way to perform geographic data analysis, data conversion, data management, and map automation with Python.
ArcPy provides access to geoprocessing tools as well as additional functions, classes, and modules that allow you to create simple or complex workflows quickly and easily.
ArcGIS applications and scripts written using ArcPy benefit from being able to access and work with the numerous Python modules developed by GIS professionals and programmers from many different disciplines. The additional power of using ArcPy within Python is the fact that Python is a general-purpose programming language that is easy to learn and use. It is interpreted and dynamically typed, which provides you with the ability to quickly prototype and test scripts in an interactive environment while still being powerful enough to support the writing of large applications.
ArcPy provides access to geoprocessing tools as well as additional functions, classes, and modules that allow you to create simple or complex workflows. Broadly speaking, ArcPy is organized in tools, functions, classes, and modules.
Technically speaking, geoprocessing tools are functions available from arcpy—that is, they are accessed like any other Python function. However, to avoid confusion, a distinction is always made between tool and nontool functions (such as utility functions like ListFeatureClasses()).
- Tools are documented differently than functions. Every tool has its own tool reference page in the ArcGIS Desktop help system. Functions are documented in the ArcPy documentation.
- Tools return a Result object; functions do not.
- Tools produce messages, accessed through a variety of functions such as GetMessages(). Functions do not produce messages.
- Tools are licensed by product level (ArcGIS for Desktop Basic, Standard, or Advanced) and by extension (ArcGIS Network Analyst extension, ArcGIS Spatial Analyst extension, and so on). You can find what license levels are required on the tool's reference page. Functions are not licensed—they are installed with ArcPy.
Running a tool
This next example shows how to execute the Buffer tool. As the tool executes, the messages will appear by default on the right side of the Python window in the help section.
>>> arcpy.Buffer_analysis("c:/data/Portland.gdb/streets", "c:/data/Portland.gdb/steets_buffer", "500 METERS")
Here is another example of running tools. This example uses tools in the data management and conversion toolboxes. A field is added to the input streets feature class, the field is calculated, and the feature class is then loaded into an ArcSDE enterprise geodatabase.
>>> import arcpy
>>> arcpy.AddField_management("c:/data/Portland.gdb/streets", "LENGTH_MILES", "TEXT")
>>> arcpy.CalculateField_management("c:/data/Portland.gdb/streets", "LENGTH_MILES", "!shape.length@miles!", "PYTHON_9.3")
>>> arcpy.FeatureClassToFeatureClass_conversion("c:/data/Portland.gdb/streets", "Database Connections/MySDE.sde/PortlandDataset", "streets")
Getting results from a tool
When a geoprocessing tool is executed, the results of the tool are returned in a result object. Typically, this object is the path to the output dataset produced or updated by the tool. In other cases, it may contain other value types, such as a number or Boolean. If an output for a tool is a multivalue parameter, the values can be returned as a list within a list.
The following code examples show how return values are captured and what their values could be:
Return the path of the output feature class. The result can be used as input to another function.
>>> result = arcpy.Buffer_analysis("rivers", "riverBuf", "50 METERS")
>>> print result
C:\Portland\Portland_OR.gdb\riverBuf
>>> arcpy.Clip_analysis("streets", result, "streets_50m_of_rivers")
Return the number of features.
>>> result = arcpy.GetCount_management("streets_50m_of_rivers")
>>> print result.getOutput(0)
54
Return a list of default spatial grid indexes for a feature class.
>>> result = arcpy.CalculateDefaultGridIndex_management("streets_50m_of_rivers")
>>> for i in range(0, result.outputCount):
... print result.getOutput(i)
...
560
200
0
Using environment settings
Geoprocessing environment settings can be thought of as additional parameters that affect a tool's results. They differ from normal tool parameters in that they are set separately from the tool and are interrogated and used by tools when they are run. Environment settings, such as an area of interest, the coordinate system of the output dataset, and the cell size of a new raster dataset, can all be specified and honored by the tools.
Environment settings are available from the env class as properties. These properties can be used to retrieve the current environment values and set them. Below are examples of how to use environment values:
Set the workspace environment.
>>> arcpy.env.workspace = "c:/data/Portland.gdb"
>>> arcpy.Buffer_analysis("streets", "streetBuf", "500 METERS")
Set the spatial grid index to the return value of a tool.
>>> arcpy.env.spatialGrid1 = arcpy.CalculateDefaultSpatialGridIndex_management("streets").getOutput(0)
Get the current raster cell size setting and make sure it is a specific size for standard output.
if arcpy.env.cellSize != 30:
arcpy.env.cellSize = 30
Using functions
A function is a defined bit of functionality that does a specific task and can be incorporated into a larger program. In addition to tools, ArcPy exposes a number of functions to better support geoprocessing workflows. Functions can be used to list certain datasets, retrieve a dataset's properties, check for existence of data, validate a table name before adding it to a geodatabase, or perform many other useful scripting tasks.
The example code below shows getting the properties of data and checking out an extension:
import arcpy
# prints True
print arcpy.Exists("c:/data/Portland.gdb/streets")
# prints NAD_1983_StatePlane_Oregon_North_FIPS_3601_Feet
sr = arcpy.Describe("c:/data/Portland.gdb/streets").spatialReference
print sr.name
# prints Available
print arcpy.CheckExtension("spatial")
arcpy.CheckOutExtension("spatial")
Using classes
ArcPy classes, such as the SpatialReference and Extent classes, are often used as shortcuts to complete geoprocessing tool parameters that would otherwise have a more complicated string equivalent. A class is analogous to an architectural blueprint. The blueprint provides the framework for how to create something. Classes can be used to create objects; this is often referred to as an instance.
import arcpy
spatial_ref = arcpy.SpatialReference("Hawaii Albers Equal Area Conic")
Working with modules
ArcPy includes modules covering other areas of ArcGIS. ArcPy is supported by a series of modules, including a data access module (arcpy.da), a mapping module (arcpy.mapping), an ArcGIS Spatial Analyst extension module (arcpy.sa), and an ArcGIS Network Analyst extension module (arcpy.na).
For example, the tools of the arcpy.sa module use tools in the Spatial Analyst toolbox but are configured to support Map Algebra. Thus, executing arcpy.sa.Slope is the same as executing the Slope tool from the Spatial Analyst toolbox.