Select to view content in your preferred language

Variables in Select by Attribute Where Clause

5575
11
Jump to solution
09-01-2023 01:17 PM
andrewcollins12
Emerging Contributor

Hello!

I'm having a heck of a time (read: I'm about to throw my computer down the stairs) trying to use two variables (both field and value) in a Select by Attribute query. I'm working in ArcGIS Pro 3.1/Python 3.9.

Here's the use case: I want to select points with a given value in a given field from a large grid of points in a point shapefile, and then export those points to a new shapefile. Most recent code attempt below.

 

import arcpy
import os

# Input point shapefile, very large
grid = arcpy.GetParameterAsText(0) 

# Specific area where I want to extract points with certain value
aoi = arcpy.GetParameterAsText(1) 

# Field in grid to use for values to query (dtype = double)
repl_field = arcpy.GetParameterAsText(2) 

# User-specified value to match with points to export (dtype = double)
value = arcpy.GetParameter(3) 

# Scratch workspace for intermediate data/debugging
ws = arcpy.GetParameterAsText(4) 

# Intermediate files
int_grid = os.path.join(ws, "int_grid.shp")
final_grid = os.path.join(ws, "final_grid.shp")

# Step 1: extract just the points inside AOI; this works as expected
arcpy.management.SelectLayerByLocation(grid,"COMPLETELY_WITHIN",aoi,"","NEW_SELECTION")
arcpy.conversion.ExportFeatures(grid,int_grid)

# Step 2: this selection isn't working; all points are exported, 
# not just those that match value.
where_clause = '"{}" = {}'.format(repl_field,value)
arcpy.management.SelectLayerByAttribute(int_grid,"NEW_SELECTION",where_clause)
arcpy.conversion.ExportFeatures(int_grid,final_grid)

 

 

I've also tried the methods commented here, here, and here (basically all just different ways of formatting the where clause), with no luck. No matter how I format it, I just can't get it to select and export the correct data.

When I enter this code (and several other versions) line-by-line in the Python console in ArcGIS Pro, it works perfectly. But I need it to run in this script. I'm thoroughly at a loss and would be very appreciative of any suggestions.

0 Kudos
11 Replies
JingchaoZhou
Occasional Contributor

You mentioned that the script works if you run them line by line in the python window, but did not work as a script.

I was wondering whether you ran the script in the python window or as a standalone script outside of ArcGIS Pro?

0 Kudos
andrewcollins12
Emerging Contributor

Both. When I ran the code in the original post line-by-line in the python window within ArcGIS Pro, it all ran correctly. But something was breaking with the select functions when I ran it as a standalone script outside of Arc Pro. The solution proposed by @AlfredBaldenweck--to assign the selection to a variable--enabled me to run it as a standalone script.

0 Kudos