0

I have a simple script that I'm running as an ArcGIS tool that adds three fields and then calculates the fields based on expressions that derive information from existing fields. I'm struggling to understand why the script only works if it is run twice. The first time the script is run it adds the fields. The second time the script runs, the fields are populated. Any ideas on how I can get this code to work in a single run? Note: You can ignore the altercounty() function; it works and is more or less a rider on the script.

EDIT

Removed the try/except handlers as suggested and receive the following error:

ExecuteError: Failed to execute. Parameters are not valid. ERROR 000728: Field TownshipNum does not exist within table Failed to execute (CalculateField).

Still working if it's run twice.

import arcpy

Section = arcpy.GetParameter(0)
County = arcpy.GetParameter(1)


def addfields():
    if arcpy.Exists(Section):
        fieldlist = [str(f.name) for f in arcpy.ListFields(Section)]
        if 'TownshipNum' not in fieldlist:
            arcpy.AddField_management(Section, "TownshipNum", "TEXT", "", "", "5", "TownshipNum", "NULLABLE",
                                      "NON_REQUIRED")
            arcpy.AddMessage("\n" + "Field: TownshipNum SUCCESSFULLY ADDED!")
    else:
        arcpy.AddMessage("\n" + "Field TownshipNum already exists.")


    if 'RangeNum' not in fieldlist:
        arcpy.AddField_management(Section, "RangeNum", "TEXT", "", "", "5", "RangeNum", "NULLABLE", "NON_REQUIRED")
        arcpy.AddMessage("\n" + "Field: RangeNum SUCCESSFULLY ADDED!")

    else:
        arcpy.AddMessage("\n" + "Field RangeNum already exists.")


    if 'SectionNum' not in fieldlist:
        arcpy.AddField_management(Section, "SectionNum", "TEXT", "", "", "4", "SectionNum", "NULLABLE",\
                                  "NON_REQUIRED")
        arcpy.AddMessage("\n" + "Field: SectionNum SUCCESSFULLY ADDED!")

    else:
        arcpy.AddMessage("\n" + "Field SectionNum already exists." + "\n")
    return


else:
    arcpy.AddMessage("Section not input.")


# Calculate PLSS numbers for each field
def calcfields():

    if arcpy.Exists(Section):
        fieldlist = [str(f.name) for f in arcpy.ListFields(Section)]
        arcpy.AddMessage(fieldlist)

        twnspexp = "!lndkey![6:8] + !lndkey![9]"
        if 'TownshipNum' in fieldlist:
            arcpy.CalculateField_management(Section, "TownshipNum", twnspexp , "PYTHON")
            arcpy.AddMessage("\n" + "TownshipNum successfully calculated!")

        else:
            arcpy.AddWarning("\n" + "WARNING: Field TownshipNum not in table.")
            pass
        rangeexp = "!lndkey![11:13] + !lndkey![-1]"
        if 'RangeNum' in fieldlist:
            arcpy.CalculateField_management(Section, "RangeNum", rangeexp, "PYTHON")
            arcpy.AddMessage("\n" + "Field RangeNum successfully calculated!")

        else:
            arcpy.AddWarning("\n" + "WARNING:Field RangeNum not in table.")
            pass
        sectexp = "!sectn![1:]"
        if 'SectionNum' in fieldlist:
            arcpy.CalculateField_management(Section, "SectionNum", sectexp , "PYTHON")
            arcpy.AddMessage("\n" + "Field SectionNum successfully calculated.")
            pass

        else:
            arcpy.AddWarning("\n" + "WARNING: Field SectionNum not in table.")

addfields()
calcfields()

closed as unclear what you're asking by Jyler, John Powell, PolyGeo Apr 24 '16 at 22:41

Please clarify your specific problem or add additional details to highlight exactly what you need. As it's currently written, it’s hard to tell exactly what you're asking. See the How to Ask page for help clarifying this question. If this question can be reworded to fit the rules in the help center, please edit the question.

  • 2
    remove your try, except and finally to help you debug - these can often mask error messages – Midavalo Apr 7 '16 at 20:12
  • @Midavalo All of them or just at the end when I call functions? – Jyler Apr 7 '16 at 20:13
  • 2
    all of them, just in order to help debug the script (comment them out and fix indentation so you can re-add them if required later) – Midavalo Apr 7 '16 at 20:14
  • Please remove the try/except/finally statements from the code presented here. That way the error you present will be coming from the same code. What you present should not be your whole script. It should be a code snippet that illustrates the problem you are seeing with your script. – PolyGeo Apr 7 '16 at 20:39
  • I suspect an order-of-operations error, but can't tell with the way your script is presented in the question. – Mintx Apr 7 '16 at 21:13
1

Your def addfields section has quite a few indenting errors. Try cleaning that up and see if that fixes it.

def addfields():
    if arcpy.Exists(Section):
        fieldlist = [str(f.name) for f in arcpy.ListFields(Section)]
        if 'TownshipNum' not in fieldlist:
            arcpy.AddField_management(Section, "TownshipNum", "TEXT", "", "", "5", "TownshipNum", "NULLABLE",
                                      "NON_REQUIRED")
            arcpy.AddMessage("\n" + "Field: TownshipNum SUCCESSFULLY ADDED!")
        else:
            arcpy.AddMessage("\n" + "Field TownshipNum already exists.")


        if 'RangeNum' not in fieldlist:
            arcpy.AddField_management(Section, "RangeNum", "TEXT", "", "", "5", "RangeNum", "NULLABLE", "NON_REQUIRED")
            arcpy.AddMessage("\n" + "Field: RangeNum SUCCESSFULLY ADDED!")

        else:
            arcpy.AddMessage("\n" + "Field RangeNum already exists.")


        if 'SectionNum' not in fieldlist:
            arcpy.AddField_management(Section, "SectionNum", "TEXT", "", "", "4", "SectionNum", "NULLABLE",\
                                      "NON_REQUIRED")
            arcpy.AddMessage("\n" + "Field: SectionNum SUCCESSFULLY ADDED!")

        else:
            arcpy.AddMessage("\n" + "Field SectionNum already exists." + "\n")
        return


    else:
        arcpy.AddMessage("Section not input.")
  • No dice. Same issue persists. – Jyler Apr 8 '16 at 13:28
0

Do you need to have them in two separate functions? You could combine them into one segment:

if 'TownshipNum' not in fieldlist:
    arcpy.AddField_management(Section, "TownshipNum", "TEXT", "", "", "5", "TownshipNum", "NULLABLE","NON_REQUIRED")
    arcpy.CalculateField_management(Section, "TownshipNum", twnspexp , "PYTHON")
    arcpy.AddMessage("\n" + "Field: TownshipNum SUCCESSFULLY ADDED!")
else:
    arcpy.CalculateField_management(Section, "TownshipNum", twnspexp , "PYTHON")
    arcpy.AddMessage("\n" + "Field TownshipNum already exists.")

You could also check that AddField has succeeded by returning a True or False before calculating the fields.

if addfields():
    calcfields()

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