[GIS] Getting layer name of selected features with ArcPy

arcgis-10.2arcpypython-addin

I'm working on Python add-in that changes geometry of an object (polygon orthogonalization). The tool itself works properly when I give it an input line of layer name (or just drag layer from table of contents to script window).

Now I need to deal with single selected feature from unknown layer. For example I have 10 layers in the current mxd, edit session started for 5 of them and I need the one which feature is selected from.

How to get a layer name of current selected feature?

UPD. So what i have now. When tool works from toolbox it have an input parameter layer which is further converted to path:

layer = arcpy.GetParameterAsText(0)
dsc = arcpy.Describe(layer)
layerName = dsc.baseName
fd = dsc.path
layerPath = os.path.join(fd, layerName)

This works good when I execute this tool from toolbox for all the layer contents. This tool can also work with only selected features and I already tested it by replacing all the input with a strict line layer = "building" and adding this layer to TOC.

Now I'm trying to edit this tool to work as add-in with button.

What I need now is to know how to get a layer name when I simply select one polygone from some layer.

Best Answer

The pythonaddins module has a function to do just this, GetSelectedTOCLayerOrDataFrame():

>>> import pythonaddins
>>> sel = pythonaddins.GetSelectedTOCLayerOrDataFrame()
>>> print sel
Exported_Data
>>> 

enter image description here

Related Question