1

I'm a Python beginner working with arcpy. I want to take a selected shapefile and add an area field to it, and then populate that field.

As of now, my code only works if I have the selected layer as a parameter input by the user. If I substitute that for the "selected layer" (which is commented out right now), the field is created, but it does not populate. I cannot figure out why.

What do I need to do in order to make this work?

import time, arcpy, sys, os, pythonaddins

## Set parameters

mxd = arcpy.mapping.MapDocument("CURRENT")
df = arcpy.mapping.ListDataFrames(mxd)[0]
mxdName = os.path.basename(mxd.filePath)
directory = os.path.dirname(mxd.filePath)
layers = arcpy.mapping.ListLayers(mxd, "*", df)
arcpy.env.overwriteOutput = False
#####SelectedLayer = pythonaddins.GetSelectedTOCLayerOrDataFrame()
SelectedLayer = arcpy.GetParameterAsText(0)
f_name = "Area_ha"
f_type = "DOUBLE"
f_precision = 5
f_scale = ""
f_length = ""
f_alias = ""
f_null = "NULLABLE"
f_required = "NON_REQUIRED"
f_domain = ""

## Create Area field, calculate area in hectares

arcpy.AddField_management(SelectedLayer, f_name, f_type, f_precision, 
f_scale, f_length, f_alias, f_null, f_required, f_domain)
areaexpression1 = "{0}".format("!SHAPE.area@HECTARES!")
arcpy.CalculateField_management(SelectedLayer, f_name, areaexpression1, 
"PYTHON_9.3", "")  
2
  • 1
    Welcome to GIS SE! As a new user please take the tour to learn about our focused Q&A format. Please replace the image of your script in your question with text copy/pasted in. You can edit your question to add your code, and then select it and use the {} button to format it as code.
    – Midavalo
    Commented Apr 7, 2017 at 19:06
  • I have pasted your code as text from the image - hopefully I haven't introduced typos
    – Midavalo
    Commented Apr 9, 2017 at 3:18

1 Answer 1

1

The pythonaddins module is intended only for use within a Python add-in and cannot be used in a script tool (see the note at the top of the linked page).

You will therefore have to make an add-in to use the GetSelectedTOCLayerOrDataFrame functionality or you can continue to use a script tool and get the input from the user with arcpy.GetParameterAsText(0)

Not the answer you're looking for? Browse other questions tagged or ask your own question.