2

My script selects by date in a points layer, then creates a new layer made only of those points. The script then exports the attribute table for the new layer to Excel, turns off the original layer, and formats labels for the new layer so it can be printed to PDF and appended to a report.

I'm having issues with the lblClass.expression piece. With the desired field hardcoded, it works perfectly; however, I want the field to be a variable input in the script tool - I'm designing this for other staff to use and have no guarantees that the date field in the input layer will always be labeled consistently.

How do I insert a variable into the expression? Current (failed) attempt below.

import arcpy
import datetime
from datetime import date

# set input variables
inputLayer = arcpy.GetParameterAsText(0)
inputDate = arcpy.GetParameterAsText(1)
output = arcpy.GetParameterAsText(2)
labelField = arcpy.GetParameterAsText(3)

# set project and map variables
aprx = arcpy.mp.ArcGISProject('CURRENT')
m = aprx.listMaps('*')[0]

# inputDate formatting
inputDateTwo = '0' + inputDate
tempDate = datetime.datetime.strptime(inputDateTwo, "%m/%d/%Y")
inputDatePlusDay = tempDate + datetime.timedelta(days=1)

# convert input date to hyphen format for use in output file names
tempDateTwo = datetime.datetime.strptime(inputDateTwo, "%m/%d/%Y").strftime('%Y-%m-%d')

# selects by expression and creates a new layer from selected dates in inputLayer and adds to map
newLayer = arcpy.management.MakeFeatureLayer(inputLayer, tempDateTwo, 'Date >= \''+format(tempDate.strftime("%Y/%m/%d"))+'\' AND Date < \''+format(inputDatePlusDay.strftime("%Y/%m/%d"))+'\'').getOutput(0)
m.addLayer(newLayer)

# export new layer attribute table to Excel file
outXLSX = output + '\\' + tempDateTwo + '.xlsx'
arcpy.conversion.TableToExcel(tempDateTwo, outXLSX)

# turn off original layer
lyrList = m.listLayers('Daily Reports')
for lyr in lyrList:
   lyr.visible = False

# choose, format, and activate labels in new layer
for lyr2 in m.listLayers(tempDateTwo):
    lblClass = lyr2.listLabelClasses()[0]
    print(lblClass.name)
    lblClass.expression = "\"<FNT name='Arial' size = '6'>\" + $feature[{0}.format(labelField)] + \"</FNT>\""
    lyr2.showLabels = True'

To clarify, I'm only concerned with this input: arcpy.GetParameterAsText(3). I want to have an input that chooses the field that labels the output points. An example input would be "Test" or "Test Number." The code doesn't throw an error; it simply doesn't label the output points. The other inputs work fine, and every other part of the code works.

2
  • Can you edit your question to include samples of what you parameter inputs would be. It is difficult to try and debug when one does not know what the input could be? For example is parameter 1 20230509 or 9th May 2023, or 9/5/23? Also are you saying that the only part of the code that is failing is when you set the label expression? So all the selecting of newlayer and exporting to excel ran as expected? Whats the error message?
    – Hornbydd
    May 9, 2023 at 11:01
  • To clarify, I'm only concerned with this input: arcpy.GetParameterAsText(3). I want to have an input that chooses the field that labels the output points. An example input would be "Test" or "Test Number." The code doesn't throw an error; it simply doesn't label the output points. Will edit the question to include this as well. The other inputs work fine.
    – Skel80
    May 9, 2023 at 20:58

1 Answer 1

1

Below is a minimal amount of code to achieve the labelling you wanted. In my example I just filter by object ID where your where clause is filtering on date. The issue with your original code was that you were embedding the variable that held the field name within the text, so it is seen as text. What you need to do is concatenate the expression as a sequence of strings, so in the code below note my lableField variable is outside the expression string I build. Also the sequence of operations is important. I create the new layer object, change its labelling THEN add it to the map.

import arcpy
arcpy.env.addOutputsToMap = False

# Get map
aprx = arcpy.mp.ArcGISProject('CURRENT')
myMap = aprx.listMaps('*')[0]

# Set some objects
labelField = "OBJECTID"  # This field name comes from your GetParameterAsText(3)
aLayer = "bng_dhs_2018"

# Create a copy of layer but filtered to first 10 rows, your query is about dates
sQuery = 'OBJECTID < 10'
res = arcpy.MakeFeatureLayer_management(aLayer, "aNewLayer", sQuery)
aNewLayer = res.getOutput(0)

# Turn off visibility of original layer
lyr = myMap.listLayers(aLayer)[0]
lyr.visible = False

# Update the default label class for new layer
lstLblCLasses = aNewLayer.listLabelClasses('*')
lblClass = lstLblCLasses[0]
lblClass.visible = True
lblClass.name = "My New label"
lblClass.expression = "\"<FNT name='Arial' size = '6'>\" + $feature." + labelField + " + \"</FNT>\""

# Now you add the layer
aNewLayer.showLabels = True
myMap.addLayer(aNewLayer)

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.