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.
Solved! Go to Solution.
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?
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.