ArcPy Scripting – Using GetParameterAsText and SelectLayerByAttribute in ArcPy

arcpyparameterspython-script-toolselect-by-attribute

I have written a Python script tool wherein a user specifies a feature class (e.g., Landuse) containing different attributes (e.g., parcel size, landcover etc.), name of the attribute field from which features will be selected (e.g., "landcover") and the name of the attribute to be selected (e.g., "forest" or "buildings"). The end result should be that the script selects all the features with the specified attribute and create a new feature class out of it. For this I have 3 input parameters, as shown below, and the script receives the input with GetParameterAsText().

Parameters

My code block looks like follows:

FClass = arcpy.GetParameterAsText(0) 
Field = arcpy.GetParameterAsText(1) 
Feature = arcpy.GetParameterAsText(2)

arcpy.MakeFeatureLayer_management(FClass, "FclassLayer")
arcpy.SelectLayerByAttribute_management("FclassLayer","NEW_SELECTION","'Field' = 'Feature'")

arcpy.CopyFeatures_management("FclassLayer", "Feature1.shp")

When I run the script tool, it doesn't produce any error message and creates Feature1.shp, but the shapefile is simply a copy of the specified feature class. That means, SelectLayerByAttribute is simply selecting the whole feature class irrespective of the specified attribute.

Being a beginner with Python scripting, I am not being able to locate what am I doing wrong here. Furthermore, I tested the same script with hard coded values instead of getting it from user with GetParameterAsText, and there it runs perfectly and gets me the output as expected.

Best Answer

The problem lies in your SelectLayerByAttribute line.

Your query "'Field' = 'Feature'" indicates that you want to select all features in which attribute Field contains the string Feature. This ends up selecting nothing (presumably no fields are named Field and/or contain 'Feature'), and so the CopyFeatures step copies everything in the feature layer.

Since you want those to be treated as variables, try instead:

"{} = '{}'".format(Field, Feature)      # if querying a GDB
'"{}" = \'{}\''.format(Field, Feature)  # if querying a shapefile

That will substitute the user-supplied parameters into the string, and should correctly query, select, and copy.

(If you want to get fancy and always guarantee you have the correct field delimiters regardless of data source, check out this answer.)