Check if any features are selected

7674
8
Jump to solution
04-04-2012 11:49 AM
Zeke
by
Regular Contributor III
I want to check if any features in a feature class are selected, and exit the script with a message to the user if they aren't. But I can't find a function that checks if any features are selected. The code below gives a count of selected features, if any are, but it also returns a count of all features (~27k+) if none are. This defeats the purpose of the if statement.

Is there a way to just check if any are selected - a HasSelected type of property? Thanks.

# check how many parcels are selected     count = int(arcpy.GetCount_management("Parcel").getOutput(0)) # returns count of all parcels if none selected. This makes if statement always true, regardless if any parcels are selected      # if no parcels are selected, inform user and exit script     if count < 1:         arcpy.AddError("No features selected! \n Please select at least one parcel feature. \n")         arcpy.AddError("Quitting the Create Case tool \n")         sys.exit("Goodbye! Try again!")
Tags (2)
0 Kudos
1 Solution

Accepted Solutions
DarrenWiens2
MVP Honored Contributor
The arcpy Layer object has a property called FIDSet that is "A semicolon-delimited string of selected feature IDs (record numbers)." So, you should be able to test against that to either count selected or determine if any features are selected.

View solution in original post

8 Replies
DarrenWiens2
MVP Honored Contributor
The arcpy Layer object has a property called FIDSet that is "A semicolon-delimited string of selected feature IDs (record numbers)." So, you should be able to test against that to either count selected or determine if any features are selected.
curtvprice
MVP Esteemed Contributor
I want to check if any features in a feature class are selected, and exit the script with a message to the user if they aren't.


I think a good approach to try would be to switch the selection.

UPDATE: code repaired to add "_management" to tool call, see post below

# check how many parcels are selected
count1 = int(arcpy.GetCount_management("Parcel").getOutput(0)) 
arcpy.SelectLayerByAttribute_management("Parcel","SWITCH_SELECTION") # switch selection
count2 = int(arcpy.GetCount_management("Parcel").getOutput(0)) 
arcpy.SelectLayerByAttribute_management("Parcel","SWITCH_SELECTION") # switch it back 
# if no parcels are selected, inform user and exit script
if count1 == 0 or count2 == 0:
    arcpy.AddError("No features selected! \n Please select at least one parcel feature. \n")
    arcpy.AddError("Quitting the Create Case tool \n")
else:
    ....
0 Kudos
Zeke
by
Regular Contributor III
Thanks, the FIDSet worked. I tried switching selections, but that raised an error on SelectLayerByAttribute - module has no attribute, and although it seems like it would be necessary to select an attribute, I don't see where it's required for that function in help.
Anyway, thanks for the help, I really appreciate it. I'm trying to idiot-proof the script, and feel very qualified to test that.  I have another question as to why GetParameterAsText retrieves the value entered ok, but will strip off all characters before a final "-" when I use CalculateField to set the field value, but I'll post that in another thread if I can't figure it out.
0 Kudos
curtvprice
MVP Esteemed Contributor
I tried switching selections, but that raised an error on SelectLayerByAttribute - module has no attribute


This was my bad. Still getting used to arcpy syntax, which if you don't import the managment module requires you to specify it: SelectLayerByAttribute_management

I repaired the code sample above.
0 Kudos
Zeke
by
Regular Contributor III
Thanks, I'll try that. Surprised I didn't see it myself. Maybe I should actually look before I just copy & paste... 😉
0 Kudos
ABishop
MVP Regular Contributor

Hello @Zeke  and @DarrenWiens2 ,

I am working on a similar script but instead of just listing the selection, I want to use it as a logical parameter for executing "Calculate Geometry Attributes" on a parcel polygon.

So far I have built a model which works OK, except I get a field character count warning 🙄 When I export the model as a python script (see python window for the model script), I get an error saying this:

  File "<string>", line 6
def # NOT IMPLEMENTED# Function Body not implemented
^
SyntaxError: invalid syntax

# -*- coding: utf-8 -*-
"""
Generated by ArcGIS ModelBuilder on : 2021-09-17 08:27:10
"""
import arcpy
def #  NOT  IMPLEMENTED# Function Body not implemented

def GeometryCalc():  # GeometryCalc

    # To allow overwriting outputs change overwriteOutput option to True.
    arcpy.env.overwriteOutput = False

    arcpy.ImportToolbox(r"c:\program files\arcgis\pro\Resources\ArcToolbox\toolboxes\Data Management Tools.tbx")
    # Model Environment settings
    with arcpy.EnvManager(scratchWorkspace=r"C:\Users\abishop\AppData\Local\Temp\ArcGISProTemp10544\1ba0f558-c873-4c6c-be6d-dc08393016c0\Default.gdb", workspace=r"C:\Users\abishop\AppData\Local\Temp\ArcGISProTemp10544\1ba0f558-c873-4c6c-be6d-dc08393016c0\Default.gdb"):
        parcel = "I:\\users\\abishop\\DATA\\CadastreCopy.gdb\\parcel"

        # Process: Select Layer By Attribute (Select Layer By Attribute) (management)
        parcel_Layer, Count = arcpy.management.SelectLayerByAttribute(in_layer_or_view=parcel, selection_type="NEW_SELECTION", where_clause="GIS_ACRES IS NULL", invert_where_clause="")

        # Process: If Selection Exists (If Selection Exists) ()
        True_48, False_49 = #  NOT  IMPLEMENTED(in_layer_or_view=parcel_Layer, selection_condition="EXISTS", count=0, count_min=0, count_max=0)

        # Process: Calculate Geometry Attributes (Calculate Geometry Attributes) (management)
        if True_48:
            parcel_Layer_2_ = arcpy.management.CalculateGeometryAttributes(in_features=parcel_Layer, geometry_property=[["GIS_ACRES", "AREA"]], length_unit="", area_unit="ACRES", coordinate_system="PROJCS[\"NAD_1983_StatePlane_Florida_West_FIPS_0902_Feet\",GEOGCS[\"GCS_North_American_1983\",DATUM[\"D_North_American_1983\",SPHEROID[\"GRS_1980\",6378137.0,298.257222101]],PRIMEM[\"Greenwich\",0.0],UNIT[\"Degree\",0.0174532925199433]],PROJECTION[\"Transverse_Mercator\"],PARAMETER[\"False_Easting\",656166.6666666665],PARAMETER[\"False_Northing\",0.0],PARAMETER[\"Central_Meridian\",-82.0],PARAMETER[\"Scale_Factor\",0.9999411764705882],PARAMETER[\"Latitude_Of_Origin\",24.33333333333333],UNIT[\"Foot_US\",0.3048006096012192]]", coordinate_format="SAME_AS_INPUT")[0]

if __name__ == '__main__':
    GeometryCalc()

 

Amanda Bishop, GISP
0 Kudos
DarrenWiens2
MVP Honored Contributor

The line ("def #...") is not valid Python syntax. For some reason, exporting to Python script has malfunctioned - it has lots of problems. If there's supposed to be a function there, you'll have to write it yourself. If not, delete that line and continue on.

edit: I'm pretty sure you'll also have to edit the line "True_48, False_49 = #" 

ABishop
MVP Regular Contributor

The problem with changing or eliminating the True False is that the logical condition of checking the selection will be eliminated.  I think that's why there is a malfunction.  That logical operator I used in the ModelBuilder "If Selection Exists" only works in ModelBuilder. 😥

Amanda Bishop, GISP
0 Kudos