2

Working in ArcGIS Pro with ArcPy, I'm trying to create a script that creates a density based clustering, performs a select layer by attribute on it and then takes the extent of that selection and use it for my layout.

When run as a script from my toolbox, the script runs without fail except that it doesn't select any features. If I paste the code into the Python window it works 100% correctly and actually selects the features.

My code looks something like this:

#Import necessary modules
import arcpy
import os

#Get project variables
arcpy.env.overwriteOutput = True
aprx = arcpy.mp.ArcGISProject('CURRENT')
maps = aprx.listMaps("Map")[0]
GDB = aprx.defaultGeodatabase
lyt = aprx.listLayouts("Boorpunten1")[0]
lyr = maps.listLayers("Boringen")[0]
mf = lyt.listElements("","Main")[0]
mf.map = maps

#Group boringen for custom mapseries
arcpy.stats.DensityBasedClustering("Boringen", "Boringen_DBC", "HDBSCAN", 4, None, 50)

#Add the created layer to the map so it can be accessed by layer/layout functions
dbc2 = arcpy.management.MakeFeatureLayer(GDB+"\\Boringen_DBC", "Boringen_DBC").getOutput(0)
maps.addLayer(dbc2,'Bottom')
dbc = maps.listLayers("Boringen_DBC")[0]

#Select features and zoom the camera to those features
arcpy.management.SelectLayerByAttribute(dbc, "NEW_SELECTION", "CLUSTER_ID = 1", None)
ex = mf.getLayerExtent(dbc, True, False)
mf.camera.setExtent(ex)

What am I missing here? My guess is it has something to do with adding the newly created layer to the map document but I feel like I covered every aspect.

2
  • Try "\"CLUSTER_ID\" = 1" if CLUSTER_ID is an integer field, "\"CLUSTER_ID\" = '1'" if it is text.
    – Bjorn
    Commented Apr 13, 2018 at 13:40
  • You say when run as a script tool it does not work, this implies you are running it on different map documents. Do the map windows all have the same name as your code is seeking "Map" and then "Main" element on layout.
    – Hornbydd
    Commented Apr 14, 2018 at 14:42

1 Answer 1

1

While I didn't manage to solve the original issue of not being able to select features in ArcPy I did found a workaround that allowed me to achieve virtually the same result, albeit a bit graceless. I didn't realise it was possible to do a selection while making a feature layer. The code then looks a bit like this:

    #Add a selection of the features of the created layer to the map
    dbc2 = arcpy.management.MakeFeatureLayer(GDB+"\\Boringen_DBC","Boringen_DBC", "CLUSTER_ID = 1").getOutput(0)
    maps.addLayer(dbc2,'Bottom')
    dbc = maps.listLayers("Boringen_DBC")[0]

    #Zoom the layout camera to the selected features
    ex = mf.getLayerExtent(dbc, True, False) 
    mf.camera.setExtent(ex) 

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.