Select to view content in your preferred language

Syntax for import statement in codeblock for python script

757
2
06-20-2013 12:11 PM
danielchaboya
Regular Contributor
I'm trying to use the CalculateField tool in a script tool and part of this includes using the arcgis.rand function.  I read somewhere that the calculate field tool has it's own globals and that I would need to use the import statement at the begining of the codeblock in order for the tool to work.  If I don't import it in the codeblock, I receive an error "Name 'arcgis' is not defined". So, can anyone help in setting the syntax for the import statement. 

This is an example from the ESRI Resource site ...

Expression:
MetersToFeet((float(!shape.area!)))

Expression Type:
PYTHON_9.3

Code Block:
import math
def MetersToFeet(area):
  return math.pow(3.2808, 2) * area


This is what I have coded ...

    expression = "id_gen()"

    codeblock = """def id_gen(size = 9, chars = string.ascii_uppercase + string.digits):
    return ''.join(random.choice(chars) for x in range (size))"""

    arcpy.CalculateField_management(sewer, fieldName, expression, "PYTHON", codeblock)
Tags (2)
0 Kudos
2 Replies
ChrisPedrezuela
Frequent Contributor
Hi Daniel,

I think your better off using arcpy.da.UpdateCursor(). So you can work directly with the data rather than call the CalculateFieldTool first from the script to do your field calculations.

Thanos

I'm trying to use the CalculateField tool in a script tool and part of this includes using the arcgis.rand function.  I read somewhere that the calculate field tool has it's own globals and that I would need to use the import statement at the begining of the codeblock in order for the tool to work.  If I don't import it in the codeblock, I receive an error "Name 'arcgis' is not defined". So, can anyone help in setting the syntax for the import statement. 

This is an example from the ESRI Resource site ...

Expression:
MetersToFeet((float(!shape.area!)))

Expression Type:
PYTHON_9.3

Code Block:
import math
def MetersToFeet(area):
  return math.pow(3.2808, 2) * area


This is what I have coded ...

    expression = "id_gen()"

    codeblock = """def id_gen(size = 9, chars = string.ascii_uppercase + string.digits):
    return ''.join(random.choice(chars) for x in range (size))"""

    arcpy.CalculateField_management(sewer, fieldName, expression, "PYTHON", codeblock)
0 Kudos
JasonScheirer
Esri Alum
Just need to import random

codeblock = """import random
def id_gen(size = 9, chars = string.ascii_uppercase + string.digits):
    return ''.join(random.choice(chars) for x in range (size))"""
0 Kudos