[GIS] How to pass only selected features in python toolbox

arcgis-10.2arcpypython-toolboxselect

I have a feature class in a file geodatabase. I want to select features from the feature class and export their attribute to an excel sheet. I need a python tool in ArcGIS which does this. My problem is, how can i pass only selected features to arcpy cursor.

In the post (Getting list of selected features in ArcGIS for Desktop using Python code?
) i read that cursor object only returns selected rows for a layer. But this does not seem to work for a feature class in file geodatabase. When i pass a feature class to search cursor it returns all the features in the feature class even when there are selected features in ArcMAP.

If you need more info feel free to ask.

code to pass the feature class to python toolbox

def getParameterInfo(self):
    param1 = arcpy.Parameter(
        displayName = "Input Feature",
        name = "in_layer",
        datatype = "DEFeatureClass",
        parameterType = "Required",
        direction= "Input")
    param1.filter.list = ["Polyline"]

   params = [param1]
   return params

def execute(self, parameters, messages):

    fc = parameters[0].valueAsText

    fields = [f.name for f in arcpy.ListFields(fc)] 
    l = [[row.getValue(field)  for row in arcpy.SearchCursor(fc)] for field in fields ]

Best Answer

When defining your parameter you need to use a layer, not a feature class, if you want to take advantage of any selections already made upon it.

def getParameterInfo(self):
    """Define parameter definitions"""
    fc = arcpy.Parameter(displayName='Features',
        name='features',
        datatype='Feature Layer',
        parameterType='Required',
        direction='Input')

I grabbed the above code from Set default values for value table in Python Toolbox tool - it looks right, with the key thing to pay attention to being datatype='Feature Layer', but I have not tested it.

Related Question