[GIS] ArcGIS Python Script, Calculate Field

arcgis-10.2arcpyfield-calculator

I am trying to write a Python Script for ArcGIS 10.2.

#import system modules 
import arcpy 
import math 
from arcpy import env 

#Set environment options 
env.workspace="C:/Users/el/ac/script1" 

# Set local variables 
inFeatures = "line2.shp" 
fieldName = "angle1" 
expression = "GetAzimuthPolyline(!Shape!)" 
codeblock = """import math 
def GetAzimuthPolyline(shape): 
    radian = math.atan((shape.lastpoint.x - shape.firstpoint.x)/(shape.lastpoint.y - shape.firstpoint.y)) 
    degrees = radian * 180 / math.pi 
    return degrees""" 


# Execute AddField 
arcpy.AddField_management(inFeatures, fieldName, "SHORT") 
#print "Field has been added." 

# Execute CalculateField 
arcpy.CalculateField_management(inFeatures, fieldName, "GetAzimuthPolyline(!Shape!)", "PYTHON", codeblock)

Field was added, but the result is not calculated and is not writing into the field. But, if I write the code block in Calculate field in ArcMap, field calculates correctly. Why?

Code was amended. But if I run the script:

Traceback (most recent call last):
  File "C:\Users\el\ac\script1\scr1.py", line 35, in <module>
arcpy.CalculateField_management(inFeatures, fieldName, "GetAzimuthPolyline(!Shape!)", "PYTHON", codeblock)
  File "c:\program files (x86)\arcgis\desktop10.2\arcpy\arcpy\management.py", line 3354, in CalculateField
    raise e
ExecuteError: ERROR 000539: Error running expression: GetAzimuthPolyline(GPVARIANTOBJECT0) 
Traceback (most recent call last):
  File "<expression>", line 1, in <module>
  File "<string>", line 3, in GetAzimuthPolyline
AttributeError: 'str' object has no attribute 'x'

Best Answer

You're using an expression type of 'PYTHON', but to support the calculation you're trying, you need to use 'PYTHON_9.3'.

Related Question