I have a script tool which is supposed to apply a definition query to all layers in a feature service in the map and then remove all empty feature layers from the Contents pane. The tool can successfully apply the definition query but fails to remove the empty layers. I put the code to remove the empty layers in a separate script tool and it works! Any idea why that code won't work in the same script as the definition query code?
def script_tool(param0, param1,param2):
"""Script code goes below"""
aprx = arcpy.mp.ArcGISProject("CURRENT")
m = aprx.activeMap
for lyr in m.listLayers():
if lyr.supports("DEFINITIONQUERY"):
#If the Clear Queries option is checked:
if param2:
lyr.definitionQuery = ""
else:
#Apply definition query to all layers in the map
lyr.definitionQuery = param1
#Remove empty layers
arcpy.conversion.ExportFeatures(lyr, "temp")
results = arcpy.GetCount_management("temp")
count = results.getOutput(0)
if count == '0':
m.removeLayer(lyr)
aprx.save()
return
if __name__ == "__main__":
param0 = arcpy.GetParameterAsText(0)
param1 = arcpy.GetParameterAsText(1)
param2 = arcpy.GetParameterAsText(2)
script_tool(param0, param1,param2)