AnsweredAssumed Answered

Python Toolbox Derived Output Issues

Question asked by gitchi on Jan 10, 2016
Latest reply on Jan 12, 2016 by rastrauch

I am creating a python toolbox in ArcGIS 10.1 and have a python script working as a stand-along script but when I try to bring it into a python toolbox the tool does OK at creating an output XYZ event theme layer with the arcpy.MakeXYEventLayer_management tool and then I do create an output fc using arcpy.FeatureClassToFeatureClass_conversion which does create the fc on disk but when I try to use this fc as input in the next process to create a new fc that uses filter (sql_where_clause) the tool can not recognize the input fc that was just created on disk.  I am new at python toolboxes and think it is likely that I am not using the tools parameters properly. After having read all of the forums etc. that I could find I still am no closer to figuring this out. When I hard code the fc paths and use those as inputs into the next tool I use in the process the code can complete OK albeit not getting it using dynamic parameters.  The majority of the code I am using is below. Any suggestions about how to use the python toolbox parameters correctly?


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

        # List of tool classes associated with this toolbox = [Tool_Test]

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

    def getParameterInfo(self):
        """Define parameter definitions"""
        params = None
        """Define well location input csv file parameter definitions"""
        # First parameter
        param0 = arcpy.Parameter(
            displayName="Input File",

        # To define a file filter that includes .csv and .txt extensions,
        #  set the filter list to a list of file extension names
        param0.filter.list = ['txt', 'csv']

        # Second parameter
        """Define derived well track fc parameter definitions"""
        param1 = arcpy.Parameter(
            displayName="Output Well Track Features",
##            datatype="GPFeatureLayer",

##        param1.parameterDependencies = []

        # Third parameter
        """Define derived well fc parameter definitions"""
        param2 = arcpy.Parameter(
            displayName="Output Well Features",
##            datatype="GPFeatureLayer",

##        param2.parameterDependencies = []

        #add each param to list
##        params = [param0, param1]
        params = [param0, param1, param2]

        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."""

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

    def execute(self, parameters, messages):
        """The source code of the tool."""
        # set local variables
        XY_Layer = 'in_file'
        out_fc_well_track = 'out_fc_well_track'
        out_fc = 'out_fc'

        # get input_fc name
        if parameters[0] != None:
            inCSV_file = parameters[0].valueAsText
            in_file_name = os.path.splitext(os.path.basename(inCSV_file))[0]
            arcpy.AddMessage("in_file_name: " + in_file_name)

            # Validate the output name so it is valid
            well_fc_name = arcpy.ValidateTableName(in_file_name)
            arcpy.AddMessage("input name validated: " + well_fc_name)

            out_fc_well_track = well_fc_name + "_well_track"
            if arcpy.Exists(out_fc_well_track):
            if arcpy.Exists(well_fc_name):

            arcpy.AddMessage("Start XYZ Tool...")
            # Make the XY event layer...
        ##    arcpy.MakeXYEventLayer_management(inCSV_file, x_coords, y_coords, XY_Layer, sr_In, z_coords)
            arcpy.MakeXYEventLayer_management(inCSV_file, "X_usft", "Y_usft", XY_Layer, sr_In, "TVD_usft")

            # create well track fc
##            arcpy.SetParameter(1,out_fc_well_track)
            arcpy.AddMessage("Start FC to FC Tool...")
            arcpy.FeatureClassToFeatureClass_conversion(XY_Layer, out_wrk_spc, out_fc_well_track)
            arcpy.AddMessage("Completed FC to FC Tool..." + out_fc_well_track)

            # create well fc
            out_fc = well_fc_name
            delimitedField = arcpy.AddFieldDelimiters(out_wrk_spc, where_field)
            sql_where = delimitedField + " IN('SHL', 'TPH', 'BHL')"
            arcpy.AddMessage("sql_where clause: " + sql_where)

            # using sql query to filter out SHL, TPH, and BHL from well track fc
            # TODO: remove hard code and use paramaters as intended...
##            out_fc_well_track = r'O:\Alaska\GIS\cook_inlet\maps\MRA\Code\TRS_Distances\data\MTRS_wells.gdb\SCU_322C_04_WP04___GIS_Format_well_track'
            arcpy.FeatureClassToFeatureClass_conversion(out_fc_well_track, out_wrk_spc, out_fc, sql_where)
##            arcpy.SetParameter(2,out_fc)
            arcpy.AddMessage("Completed FC to FC Tool..." + out_fc)

            # TODO: remove hard code and use paramaters as intended...
##            out_fc = r'O:\Alaska\GIS\cook_inlet\maps\MRA\Code\TRS_Distances\data\MTRS_wells.gdb\SCU_322C_04_WP04___GIS_Format'

            # Print the total rows
            if int(arcpy.GetCount_management(out_fc)[0]) == 0:
                arcpy.AddError("{0} has no features.".format(out_fc))
                arcpy.AddMessage('ERROR occurred because SHL, TPH, or BHL were not found in input file' )
                arcpy.AddMessage('Unable to continue! Please correct ERROR!' )
                raise arcpy.ExecuteError
                arcpy.AddMessage(out_fc + " has feature count of: " +  str(arcpy.GetCount_management(out_fc)))

             # add Well_Desc column
            arcpy.AddMessage("Adding 'Well_FC' field to well fc...")
            arcpy.AddField_management(out_fc, field_name, "TEXT", field_length=50)
            # update the new Well_Desc field
#            updateWell_Desc(out_fc)
            arcpy.AddMessage("Updated Well_Desc column!")