0

This script does not work in a Standard Toolbox but it works in a Python Toolbox.

Do I need to delete all the parameters from the script?

import arcpy, os, sys, shutil


class Toolbox(object):
    def __init__(self):
        """Define the toolbox (the name of the toolbox is the name of the .pyt file)."""
        self.label = "polyNTool"
        self.alias = ""

        # List of tool classes associated with this toolbox
        self.tools = [polyNTool]


def polyProcess(src, target):
    user_profile_path = os.environ['USERPROFILE']
    gdb = r"{}/AppData/Local/Temp/PolyChecker/PolyCheck.gdb".format(user_profile_path)

    # GDB already exists, delete it

    # if arcpy.Exists(gdb):
    #   shutil.rmtree(r"{}/AppData/Local/Temp/PolyChecker".format(user_profile_path))

    # Create fresh GDB path
    # os.makedirs(os.path.dirname(gdb))

    # Create GDB
    if not arcpy.Exists(gdb):
        if not arcpy.Exists(os.path.dirname(gdb)):
            os.makedirs(os.path.dirname(gdb))
        arcpy.CreateFileGDB_management(os.path.dirname(gdb), os.path.basename(gdb))

    arcpy.AddMessage('xxx' + str(arcpy.Exists(gdb)) + ' ' + os.path.dirname(gdb))
    arcpy.env.workspace = gdb
    arcpy.env.overwriteOutput = True

    # Script arguments
    MapUnitPolys = src
    if MapUnitPolys == '#' or not MapUnitPolys:
        MapUnitPolys = "MapUnitPolys"  # provide a default value if unspecified

    MapUnitPolys_CopyFeatures = target

    # Set Geoprocessing environments
    MapUnitPolys = MapUnitPolys

    # Validate that all Polygons have a map unit

    invalid_polygon_found = False

    with arcpy.da.SearchCursor(MapUnitPolys, ['SHAPE@', 'MapUnit', 'OBJECTID']) as cursor:
        for row in cursor:
            # arcpy.AddMessage(str(row[1]))
            # Does this Polygon have a map unit
            if row[1] == "" or row[1] == "<Null>" or row[1] is None or row[1] is 0:
                invalid_polygon_found = True
                arcpy.AddMessage('Polygon OBJECT ID:{} is missing map unit... exiting.'.format(row[2]))

    # Invalid polygons were found, terminate
    if (invalid_polygon_found):
        sys.exit(1)

    Polygon_Neighbors = "{}/polytest".format(gdb)
    Polygon_Neighbors = r"POLYTABLE"
    PolygonNeighbor_TableSelect = "{}/PolygonNeighbor_TableSelect".format(gdb)

    inFeatures_lyr = "{}/inFeatures_1yr".format(gdb)
    inFeatures_lyr = r"inFeatures_1yr"

    # Process: Polygon Neighbors
    arcpy.PolygonNeighbors_analysis(MapUnitPolys, Polygon_Neighbors, "OBJECTID;MapUnit", "NO_AREA_OVERLAP",
                                    "BOTH_SIDES",
                                    "", "METERS", "SQUARE_METERS")

    mxd = arcpy.mapping.MapDocument("CURRENT")

    df = arcpy.mapping.ListDataFrames(mxd)[0]
    arcpy.AddMessage('current ' + mxd.title + ' ' + df.name + ' ' + Polygon_Neighbors)
    pn = arcpy.mapping.TableView(Polygon_Neighbors)
    arcpy.mapping.AddTableView(df, pn)
    # for lyr in arcpy.mapping.ListLayers(mxd):
    #   arcpy.AddMessage('Map Layer: '+lyr.name)

    # Process: Select Layer By Attribute
    arcpy.SelectLayerByAttribute_management(Polygon_Neighbors, "NEW_SELECTION", "src_MapUnit = nbr_MapUnit")

    # Process: Table Select
    arcpy.TableSelect_analysis(Polygon_Neighbors, PolygonNeighbor_TableSelect, "src_MapUnit = nbr_MapUnit")

    arcpy.GetCount_management(PolygonNeighbor_TableSelect)

    arcpy.AddMessage(arcpy.GetMessages())

    if int(arcpy.GetCount_management(PolygonNeighbor_TableSelect)[0]) > 0:
        arcpy.MakeFeatureLayer_management(MapUnitPolys, inFeatures_lyr)
    else:
        print ("done")

    # Process: Add Join
    arcpy.AddJoin_management(inFeatures_lyr, "OBJECTID", PolygonNeighbor_TableSelect, "src_OBJECTID", "KEEP_COMMON")

    # Process: Copy Features
    arcpy.CopyFeatures_management(inFeatures_lyr, MapUnitPolys_CopyFeatures, "", "0", "0", "0")

    # Add to Map
    ws = arcpy.env.workspace
    lyrNew = ws + "/" + MapUnitPolys_CopyFeatures
    arcpy.AddMessage('Copy layer ' + df.name + ' Path ' + lyrNew)
    addLayer = arcpy.mapping.Layer(lyrNew)
    arcpy.mapping.AddLayer(df, addLayer)

    # Process: Remove Join
    arcpy.RemoveJoin_management(inFeatures_lyr, "")

    # Execute Delete
    arcpy.Delete_management(PolygonNeighbor_TableSelect)
    arcpy.Delete_management(Polygon_Neighbors)

    arcpy.AddMessage('All done! Check Polygons')

    return


class polyNTool(object):
    def __init__(self):
        """Define the tool (tool name is the name of the class)."""
        self.label = "polyNTool"
        self.description = ""
        self.canRunInBackground = False

    def getParameterInfo(self):
        """Define parameter definitions"""

        param0 = arcpy.Parameter(
            displayName="Source Layer",
            name="sourceLayer",
            datatype="Feature Class",
            parameterType="Required",
            direction="Input")

        param1 = arcpy.Parameter(
            displayName="Target Layer",
            name="targetLayer",
            datatype="String",
            parameterType="Required",
            direction="Input")

        params = [param0, param1]
        return params

    def isLicensed(self):
        """Set whether tool is licensed to execute."""
        return True

    def updateParameters(self, parameters):
        """Modify the values and properties of parameters before internal
        validation is performed.  This method is called whenever a parameter
        has been changed."""
        return

    def updateMessages(self, parameters):
        """Modify the messages created by internal validation for each tool
        parameter.  This method is called after internal validation."""
        return

    def execute(self, parameters, messages):
        """The source code of the tool."""
        arcpy.ResetEnvironments()
        arcpy.env.overwriteOutput = True
        src = parameters[0].valueAsText

        target = parameters[1].valueAsText
        arcpy.AddMessage('params ' + src + ' ' + target)
        # arcpy.env.workspace = cws
        status = True

        if arcpy.Exists(src):
            ps = "Found WS " + src
        else:
            ps = "Missing WS" + src
            status = False

        if status == False:
            arcpy.AddMessage(ps)
            try:
                sys.exit(0)
            except SystemExit:
                pass
        else:
            arcpy.AddMessage("Validated input ...")
            polyProcess(src, target)

        return
2

The structure of a Standard Toolbox (TBX) is quite different to that of a Python Toolbox (PYT).

You should be able to re-use most of your execute functions but parameter handling is very different.

I recommend reviewing the help on writing Python Script Tools e.g. Understanding script tool parameters.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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