[GIS] Select Layer By Attribute Python Script Tool

arcmaparcpyparameterspython-script-toolselect-by-attribute

I'm trying to script another Select by Attributes tool. I want to be able to find a specific building using a field and zoom in to the location. However, my tool needs to allow a user to input any field or any value. So far this is what I got.

#Import Modules
import arcpy

arcpy.env.workspace = "C:\Users\pierrej\Desktop\GIS Data"
arcpy.env.overwriteOutput = True


#Set to current mxd and dataframe
mxd = arcpy.mapping.MapDocument ('CURRENT')
df = arcpy.mapping.ListDataFrames(mxd,"Layers")[0]

try:
    # Set the tool parameters
    InputFeatureClass = arcpy.GetParameterAsText(0)
    InputField = arcpy.GetParameterAsText(1)
    InputValue = arcpy.GetParameterAsText(2)

    # SQL expression used in selecting a feature 
    #Create the query
    qry = "\"InputField\" = InputValue"

    arcpy.MakeFeatureLayer_management(InputFeatureClass, "Layer")

    #Call the Select Layer by Attribute tool
    arcpy.SelectLayerByAttribute_management("Layer", "NEW_SELECTION", qry)

    #Zooming to a selection set for the specific layer
    df.zoomToSelectedFeatures()
    df.scale = 2500000
    arcpy.RefreshActiveView()

    # Report a success message    
    arcpy.AddMessage("All done!")


#Print an error message in the event of a problem:
    except:
    print "An error occurred during selection"

My parameters are the following:

InputFeatureClass = Data Type: Feature Layer, Required, Input, No Multivalue

InputField = Data Type: Field, Required, Input, No Multivalue, Obtained from Input Feature Class

InputValue = DataType: String, Required, No Multivalue

The script runs and I don't have any error message but the tool doesn't select any thing. How can I fix this?

Best Answer

When you say the "tool doesnt select anything", I assume you mean you don't see a selection in the map.

It doesn't appear to select anything because you've run Make Feature Layer and and performed a selection on that layer -- that is, a layer that's local to the tool instead of the Map. You may have a layer in your map that's source points to the same input as the featureclass you provided to the tool, but you basically have two instances of these layers now.

Fix: Change the input parameter type from feature class to feature layer. Remove the Make Feature Layer call and have Select Layer by Attribute work against the input layer

Also a problem I see - how your constructing your WHERE_CLAUSE. Swap in the code block below. As right now, you're not using the inputs from the variables you've created. Right now you're using strings named "InputField" and "inputvalue"

InputField = arcpy.GetParameterAsText(1)
InputValue = arcpy.GetParameterAsText(2)

#SQL expression used in selecting a feature 
#Create the query
qry = "'{}'= {}".format(InputField, InputValue) 
Related Question