2

I am running a Field Calculation within a Python script in ArcGIS. Within this Field Calculation I am calling a defined function within a code block.

Here is the dialogue that I ran and works: enter image description here

This worked. However, I cannot get this to translate into my Python code: enter image description here

Here's the code:

#Calculate YSLB
expression = "output(!MTH_BRNT!,!YR_BRNT!,!YSLB!)"
code_block = "def output(MTH_BRNT,YR_BRNT,YSLB):/n month = str(month_val)/n month_current = int(month)/n month_fire = int(MTH_BRNT)/n year = str(high_year)/n year_current = int(year)/n year_fire = int(YR_BRNT)/n Mc = (12*(year_current-1)) + month_current/n Mf = (12*(year_fire-1)) + month_fire/n return (Mc-Mf)/12"
arcpy.CalculateField_management(fuel_age_out,"YSLB",expression,"PYTHON_9.3",code_block)
PolyGeo
  • 65,136
  • 29
  • 109
  • 338
Bryce Touchstone
  • 527
  • 3
  • 11
  • What if you use backslashes () in the code_block line instead of slashes (/)? – GISGe Apr 10 '15 at 06:03
  • Also, if you use existing variables for month, year etc, you should add the double quotes around str(month_val). I advise you to use the string.format() function when using multiples sets of quotes/double quotes. – GISGe Apr 10 '15 at 06:06

1 Answers1

3

I have met this problem before. Try to use """ instead of " above the expression.

Otherwise, try this one :

code_block = """def output(MTH_BRNT,YR_BRNT,YSLB):
 month = str(month_val)
 month_current = int(month)/n month_fire = int(MTH_BRNT)
 year = str(high_year)/n year_current = int(year)
 year_fire = int(YR_BRNT)
 Mc = (12*(year_current-1)) + month_current
 Mf = (12*(year_fire-1)) + month_fire
 return (Mc-Mf)/12"""

sometimes python doen"t rescognize the \n

S_TssG
  • 131
  • 4
  • This is a link to a Q&A here about an issue with "\n" in the field calculator, although it seems to be about when it is in the data rather than the code: http://gis.stackexchange.com/questions/44460/how-to-remove-return-newline-n-character-from-field-using-python-and-field-ca – PolyGeo Apr 10 '15 at 08:15
  • Hi, thanks! So, I just enter that as is, with a single space before each following line underneath 'code_block'? – Bryce Touchstone Apr 10 '15 at 10:24
  • Yes it'for the indention. either a space or a tab – S_TssG Apr 10 '15 at 11:23
  • Writing out the code block without "\n" solved this for me. Interestingly, this only became a problem for me in ArcMap 10.8- all earlier 10.x versions of ArcMap worked with "\n". I am also executing the tool from VB.NET, so to create the new lines in the code_block string I used VbCrLf. – isburns Apr 27 '21 at 01:19