Automating Geoprocessing with ArcPy: Buffer, Clip and Summarize

This post walks through a small ArcPy script that buffers one layer, clips another layer with the result, counts and summarizes what is left, and then repeats a clip over every feature class in a geodatabase. You will end up with a script you can run outside ArcGIS Pro and adapt to your own data.

What you need

ArcPy is not a package you can pip install. It ships with ArcGIS Pro and needs a licensed Pro installation on the machine running the script. Pro installs its own Python 3 in a conda environment called arcgispro-py3, and ArcPy only imports from that environment (or from a clone of it made with the Pro Package Manager).

You can run the scripts in this post in three ways:

  • In the Python window inside ArcGIS Pro.
  • In a Pro notebook.
  • From a command prompt with propy.bat, which ships with Pro and starts the active Pro environment. On a default install it is under C:\Program Files\ArcGIS\Pro\bin\Python\scripts\.

The license level matters for some tool options. The tools used here, Buffer and Clip with their default options, work at the Basic level. The Buffer tool page notes that the LEFT, RIGHT and OUTSIDE_ONLY side options and the FLAT end type need an Advanced license. Each tool page in the ArcGIS Pro tool reference has a licensing section; check it before you rely on an option. arcpy.ProductInfo() tells you which level the current session is using.

The task

The example uses three feature classes in a file geodatabase:

  • roads - polylines
  • parcels - polygons with a text field ZONING
  • study_area - a single polygon

The question is: which parts of which parcels lie within 50 metres of a road, and how much area of each zoning class is affected? The names and the field are placeholders; replace them with your own. The data should be in a projected coordinate system with metre units so that distances and areas mean what you expect.

Setting up the environment

import os
import sys

import arcpy

arcpy.env.workspace = r"C:\gis\project\input.gdb"
arcpy.env.overwriteOutput = True

OUT_GDB = r"C:\gis\project\output.gdb"

arcpy.env.workspace sets the default location for inputs. Once it is set, you can refer to "roads" instead of the full path. Outputs given as plain names also go there, which is why the script builds explicit output paths with os.path.join() instead.

arcpy.env.overwriteOutput = True lets tools replace existing outputs. Without it, running the script a second time fails because the output feature classes already exist. That is convenient while developing, but be careful when you point a script with this setting at data you care about.

Buffer

roads_buf = os.path.join(OUT_GDB, "roads_buf_50m")
arcpy.analysis.Buffer("roads", roads_buf, "50 Meters",
                      dissolve_option="ALL")

The full signature is arcpy.analysis.Buffer(in_features, out_feature_class, buffer_distance_or_field, {line_side}, {line_end_type}, {dissolve_option}, {dissolve_field}, {method}). The distance is a string with a value and a linear unit. If you leave the unit out, the tool uses the unit of the input's coordinate system. You can also pass a field name to buffer each feature by its own distance.

dissolve_option="ALL" merges all the buffers into one feature, so overlapping road buffers do not produce duplicate pieces later. The default, "NONE", keeps one buffer per road, and "LIST" dissolves by the values in dissolve_field. Using a keyword argument means you do not have to fill in the line side and end type positions with their defaults.

Clip

near_roads = os.path.join(OUT_GDB, "parcels_near_roads")
arcpy.analysis.Clip("parcels", roads_buf, near_roads)

Clip keeps the parts of the input features that fall inside the clip features, and copies the input's attributes. The signature is arcpy.analysis.Clip(in_features, clip_features, out_feature_class, {cluster_tolerance}). Leave cluster_tolerance alone; the documentation warns that changing it can cause failures or unexpected results.

Counting with GetCount

count = int(arcpy.management.GetCount(near_roads)[0])
print(f"{count} parcel pieces within 50 m of a road")

GetCount does not return a number. Like every geoprocessing tool, it returns a Result object, and the count is its first output, as a string. Indexing with [0] and converting with int() is the pattern used in the tool's documentation. If the input is a layer with a selection, only the selected rows are counted.

Summarizing a field with SearchCursor

For a quick summary you do not need another geoprocessing tool. A search cursor reads rows directly:

area_by_zone = {}
with arcpy.da.SearchCursor(near_roads, ["ZONING", "SHAPE@AREA"]) as cursor:
    for zoning, area in cursor:
        key = zoning or "(none)"
        area_by_zone[key] = area_by_zone.get(key, 0.0) + area

for zoning, area in sorted(area_by_zone.items(), key=lambda kv: -kv[1]):
    print(f"{zoning:<20} {area / 10_000:10.2f} ha")

Each row is a tuple in the order of the field list, so it unpacks straight into variables. SHAPE@AREA is a geometry token that returns the area of each feature as a double, in the units of the feature class's coordinate system. With metres, dividing by 10,000 gives hectares.

The with block matters. It releases the cursor and its locks when the block ends, even if an exception is raised. A leftover cursor is a common reason for a later tool failing with a schema lock error.

The zoning or "(none)" expression handles null values, which come back from the cursor as None. For larger summaries, or when you want the result as a table, the Summary Statistics tool (arcpy.analysis.Statistics) does the same job inside the geoprocessing framework.

Looping over feature classes

The same approach scales to a whole geodatabase. arcpy.ListFeatureClasses() lists the feature classes in the current workspace, optionally filtered by a wildcard and a feature type:

for fc in arcpy.ListFeatureClasses("*", "Polygon") or []:
    if fc == "study_area":
        continue
    out_fc = os.path.join(OUT_GDB, f"{fc}_study")
    arcpy.analysis.Clip(fc, "study_area", out_fc)
    n = int(arcpy.management.GetCount(out_fc)[0])
    print(f"{fc}: {n} features clipped to study area")

It returns names, not full paths, which works because the workspace is set. The or [] guards against the function returning None, which can happen if the workspace is not valid. Other useful feature types are "Point", "Polyline" and the default "All".

Handling errors

When a geoprocessing tool fails, ArcPy raises arcpy.ExecuteError. The useful information is in the tool's messages, not in the exception text, so catch that exception and print the error messages:

try:
    run()
except arcpy.ExecuteError:
    print(arcpy.GetMessages(2))
    sys.exit(1)

arcpy.GetMessages(2) returns only error messages. The severity argument filters the messages: 0 (the default) returns everything, 1 returns only warnings and 2 returns only errors. Call the arcpy function, not getMessages() on a Result: when a tool fails, no result object is created. Inside a script tool, pass the same messages to arcpy.AddError() so they show up in the geoprocessing pane.

Let other exceptions, such as a misspelled field name in the cursor, propagate with their normal traceback. Catching everything with a bare except: hides exactly the information you need.

The complete script

import os
import sys

import arcpy

arcpy.env.workspace = r"C:\gis\project\input.gdb"
arcpy.env.overwriteOutput = True

OUT_GDB = r"C:\gis\project\output.gdb"
BUFFER_DISTANCE = "50 Meters"


def run():
    roads_buf = os.path.join(OUT_GDB, "roads_buf_50m")
    arcpy.analysis.Buffer("roads", roads_buf, BUFFER_DISTANCE,
                          dissolve_option="ALL")

    near_roads = os.path.join(OUT_GDB, "parcels_near_roads")
    arcpy.analysis.Clip("parcels", roads_buf, near_roads)

    count = int(arcpy.management.GetCount(near_roads)[0])
    print(f"{count} parcel pieces within {BUFFER_DISTANCE} of a road")

    area_by_zone = {}
    with arcpy.da.SearchCursor(near_roads, ["ZONING", "SHAPE@AREA"]) as cursor:
        for zoning, area in cursor:
            key = zoning or "(none)"
            area_by_zone[key] = area_by_zone.get(key, 0.0) + area

    for zoning, area in sorted(area_by_zone.items(), key=lambda kv: -kv[1]):
        print(f"{zoning:<20} {area / 10_000:10.2f} ha")

    for fc in arcpy.ListFeatureClasses("*", "Polygon") or []:
        if fc == "study_area":
            continue
        out_fc = os.path.join(OUT_GDB, f"{fc}_study")
        arcpy.analysis.Clip(fc, "study_area", out_fc)
        n = int(arcpy.management.GetCount(out_fc)[0])
        print(f"{fc}: {n} features clipped to study area")


if __name__ == "__main__":
    try:
        run()
    except arcpy.ExecuteError:
        print(arcpy.GetMessages(2))
        sys.exit(1)

Save it as near_roads.py and run it with propy.bat near_roads.py. The output geodatabase must already exist; create it once in Pro or with arcpy.management.CreateFileGDB().

Key points

  • ArcPy needs a licensed ArcGIS Pro install and runs in Pro's conda environment; use propy.bat for scripts outside Pro.
  • Set arcpy.env.workspace for inputs and arcpy.env.overwriteOutput for repeatable runs.
  • Tools return Result objects: int(arcpy.management.GetCount(fc)[0]) gives the row count.
  • Use arcpy.da.SearchCursor in a with block for quick summaries; SHAPE@AREA gives area in the data's units.
  • Catch arcpy.ExecuteError and print arcpy.GetMessages(2) to see why a tool failed.

Comments

Popular posts from this blog

My Cloud Notes

My CSharp Notes