The Basics of a Script Tool#

script_tool

1. What is a script tool#

A script tool allows you to turn your own Python scripts and functionality into your own geoprocessing tools.

  • an integral part of geoprocessing, just like the native tools;

  • open and run it in ArcGIS Pro;

  • use it within a ModelBuiler model.

To build a script tool, we need to have the following components.

  1. The source code i.e., a Python script (.py).

  2. A custom toolbox as a container of the script tool.

  3. Definitions for the parameters in the script tool.

2. Develop a script#


Homework 1 ModelBuilder model: find census block groups without law enforcement.

Let’s recap the whole process. First, we need to set up the env.workspace.

# setup workspace
import arcpy
gdb_worksp = r"..\data\class_data.gdb"
arcpy.env.workspace = gdb_worksp

Then, let’s define the input feature classes that we will work with.

I75_fc = "I75"
blkgrp_fc = "blockgroups"
cntbnd_fc = "county_boundary"
lawenforce_fc = "law_enforcement"

Define the output feature classes.

output_gdb = r"..\data\output_data.gdb"
I75_buff = output_gdb + "\\" + "I75_Buff"
blkgrp_law = output_gdb + "\\" + "blkgrp_law"
blkgrp_select = "blockgroups_select"

We now execute geoprocessing functions in the following sequence.

# Buffer
arcpy.analysis.Buffer(I75_fc, I75_buff, "6 Miles")

# Select Layer By Location
blkgrp_lyr_1 = arcpy.management.SelectLayerByLocation(
    blkgrp_fc, "WITHIN", cntbnd_fc
)
blkgrp_lyr_2 = arcpy.management.SelectLayerByLocation(
    blkgrp_lyr_1, "WITHIN", I75_buff, selection_type="SUBSET_SELECTION"
)

# Spatial Join
arcpy.analysis.SpatialJoin(
    blkgrp_lyr_2, lawenforce_fc, blkgrp_law, 
    "JOIN_ONE_TO_ONE", "KEEP_ALL", "", "INTERSECT", "", ""
)

# Feature Class to Feature Class
query_exp = "{} = 0".format('"Join_Count"')
arcpy.FeatureClassToFeatureClass_conversion(
    blkgrp_law, output_gdb, blkgrp_select, query_exp, "", ""
)

We now have the working codes. To make it into a “Script Tool”, we need to put the codes in a python file (.py). You can either copy and paste the codes to a .py file using your favorite text editor (e.g., Visual Studio Code) or use the Export to Python File option in ArcGIS Pro.