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.