Calc fields in python

393
2
10-30-2011 08:22 AM
SylviaNiderla
New Contributor
Can someone tell me why these two calcs don't work? the "speed" one completes, but doesn't do anything. The one that calculates distance based on shapelength errors. Not sure if you can script calculate length based on shapelength in version 10.


# Description: Calculates speed and distance
#arcmap 10

 
# Import system modules
import arcpy
from arcpy import env
 
# Get user-supplied input
InputFC = arcpy.GetParameterAsText(0)

try: 
    # Calculate Speed based on time and distance
    arcpy.CalculateField_management(InputFC, "Speed", "[Time] / [Distance]", "VB") 

except:
 errMsg = arcpy.GetMessages(2)
 arcpy.AddError("Unexpected error: cannot calculate Speed" + errMsg)

try: 
    # Calculate Speed based on time and distance
    arcpy.CalculateField_management(InputFC, "Distance", "float(!SHAPE.LENGTH@kilometers)", "PYTHON")

except:
 errMsg = arcpy.GetMessages(2)
 arcpy.AddError("Unexpected error: cannot calculate Distance" + errMsg)
Tags (2)
0 Kudos
2 Replies
RichardFairhurst
MVP Honored Contributor
Can someone tell me why these two calcs don't work? the "speed" one completes, but doesn't do anything. The one that calculates distance based on shapelength errors. Not sure if you can script calculate length based on shapelength in version 10.


# Description: Calculates speed and distance
#arcmap 10

 
# Import system modules
import arcpy
from arcpy import env
 
# Get user-supplied input
InputFC = arcpy.GetParameterAsText(0)

try: 
    # Calculate Speed based on time and distance
    arcpy.CalculateField_management(InputFC, "Speed", "[Time] / [Distance]", "VB") 

except:
 errMsg = arcpy.GetMessages(2)
 arcpy.AddError("Unexpected error: cannot calculate Speed" + errMsg)

try: 
    # Calculate Speed based on time and distance
    arcpy.CalculateField_management(InputFC, "Distance", "float(!SHAPE.LENGTH@kilometers)", "PYTHON")

except:
 errMsg = arcpy.GetMessages(2)
 arcpy.AddError("Unexpected error: cannot calculate Distance" + errMsg)


The first error I will point out is that you are missing an exclamation point on your second calculation.  It should be:

    arcpy.CalculateField_management(InputFC, "Distance", "float(!SHAPE.LENGTH@kilometers!)", "PYTHON")

For the other calculation, if Distance is 0 or Null, the calculation will fail (division by 0 or Null is not allowed and the geoprocessor skips over those records).  I would think you need to reverse the calculation order, since you should want the Distance assigned before you attempt to calculate Speed.

Using the Length field directly is touchy especially if your data is stored in SDE, but it sometimes works.  However, if you apply the fixes above the calculations you have should work.
0 Kudos
SylviaNiderla
New Contributor
you were right! how obvious, guess thats why you shouldn't script late at night!

thanks a lot.
0 Kudos