1

I am trying to calculate values for a field in a python script, but keep getting an error that I don't understand:

ExecuteError: ERROR 000539: Error running expression: Fron000000F1 
Traceback (most recent call last):
  File "<expression>", line 1, in <module>
NameError: name 'Fron000000F1' is not defined
Failed to execute (CalculateField).

I can't figure out where the name 'Fron000000F1' is coming from to try and track this problem. I have tested the expression in arcmap using the field calculator with no problems. What is wrong? Code is below:

import arcpy, os, csv
arcpy.env.overwriteOutput = True

out_fc_pm = r'C:\temp\temp.gdb\SignDetect__SOL680_DD_with_PM'

def calc_id(pm,pict_fld):
  import re
  pm_patt = re.compile('\d*\.*\d*')
  pm_match = re.findall(pm_patt,pm[5:])[0]
  pm = pm_match.replace('.','')
  pm_final = pm.zfill(6)
  dir_patt = re.compile('[A-Z]\d*')
  dir_match = re.findall(dir_patt,pict_fld)[0]
  id = pict_fld[:5]+pm_final+dir_match
  if id[-1:].isdigit():
    return id
  else:
    return id+'1'

arcpy.AddField_management(out_fc_pm,'OSMI_ID','TEXT')
arcpy.CalculateField_management(out_fc_pm,'OSMI_ID',calc_id('!POSTMILE!','!Front!'),'PYTHON_9.3')

1 Answer 1

4

When using Field Calculator in ArcPy, the code block needs to be defined within the arcpy.CalculateField_management function.

Syntax:

CalculateField_management (in_table, field, expression, {expression_type}, {code_block})

So,

arcpy.CalculateField_management(out_fc_pm,'OSMI_ID',"calc_id('!POSTMILE!','!Front!')",'PYTHON_9.3',[yourcodeblock])

where [yourcodeblock] goes all on one line, and I don't want to risk mis-copying it. Per this Answer, you should be able to get the correct syntax for your script using:

run Calculate Field tool once interactively using the Expression and Code Block ... and then Copy As Python Snippet in the Geoprocessing | Results window


Side note: A complex expression seems well suited to an UpdateCursor instead of Field Calculator. (It would certainly be easier to read in your code.)

0

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.