Python Toolbox Help

3672
8
Jump to solution
12-17-2015 08:55 AM
MaryM
by
Occasional Contributor

I am trying to create my first Python Toolbox.  I have tons of ACS text file, comma field separated files.  I want my users to easily be able to join the tables to the geometry file.  My first parameter, the list of available text files is working.  Then, when I add the next parameter for the users to pick which fields they want to join from the text file as a check list is not working.  Not sure how to set this up the parameters properly?  Any help is much appreciated?

import arcpy
import os

class Toolbox(object):
    def __init__(self):
        """Define the toolbox (the name of the toolbox is the name of the
        .pyt file)."""
        self.label = "ACS_2013_5Year_Toolbox"
        self.alias = ""
        # List of tool classes associated with this toolbox
        self.tools = [ACSJoinTableTool]

class ACSJoinTableTool(object):
    def __init__(self):
        """Define the tool (tool name is the name of the class)."""
        self.label = "Join ACS Table to Census Block Group Geometry"
        self.description = "Pick a table to temporarily join to the" + \
                                     "Block Group GIS layer."
        self.canRunInBackground = False

    def getParameterInfo(self):
        """Define parameter definitions"""
        #Make parameter #0 a list of the ACS text files.
        filterList = []
        fol = r"---file path of folder containing text files here---"
        for i in os.listdir(fol):
            if i.split(".")[-1].find("txt") != -1:
                x = i.split(".")[0]
                filterList.append(x)
        filterList.sort()
        param0 = arcpy.Parameter(displayName = "Pick Table:",
                  name = "in_table",
                  datatype="GPString",
                  parameterType="Required",
                  direction="Input")
                  param0.filter.list = filterList

        #Make parameter #1 a list of the table columns
        joinTable = os.path.join(r"---file path of folder containing text files here---", param[0].valueAsText + ".txt")
        pickedTable = open(jointable,"r")
        pickedTableFields = pickedTable.readline()
        pickedTableFields = pickedTableFields.replace(",",";")
        param1 = arcpy.Parameter(displayName = "Pick Join Fields:",
                  name = "in_fields",
                  datatype="GPString",
                  parameterType="Derived",
                  direction="Input")
         param1.parameterDependencies = [param0.value]
         param1.filter.list = pickedTableFields
         parameters = [param0,param1]
          return parameters

Tags (1)
0 Kudos
1 Solution

Accepted Solutions
MaryM
by
Occasional Contributor

I figured out how to make it work in a Python Toolbox...

import arcpy
import os

class Toolbox(object):
    def __init__(self):
        """Define the toolbox (the name of the toolbox is the name of the
        .pyt file)."""
        self.label = "ACS_2013_5Year_Toolbox"
        self.alias = ""
        # List of tool classes associated with this toolbox
        self.tools = [ACSJoinTableTool]

class ACSJoinTableTool(object):
    def __init__(self):
        """Define the tool (tool name is the name of the class)."""
        self.label = "Join ACS Table to Census Block Group Geometry"
        self.description = "Pick a table to temporarily join to the" + \
                                         "Block Group GIS layer."
        self.canRunInBackground = False

     def getParameterInfo(self):
        """Define parameter definitions"""
        #Make parameter #0 a drop down list of the ACS text files and user can pick one
        filterList = []
        fol = r"---Path of Folder Containing ACS Text Files Here----"
        for i in os.listdir(fol):
            if i.split(".")[-1].find("txt") != -1:
                x = i.split(".")[0]
                filterList.append(x)
        filterList.sort()
      param0 = arcpy.Parameter(displayName = "Pick Table:",
                                                      name = "in_table",
                                                      datatype="GPString",
                                                      parameterType="Required",
                                                      direction="Output")
      param0.filter.list = filterList
    

      #Make parameter #1 filter multi-value check list a of the table columns, the user can check multiple columns
      pickTableFieldsList=[]    
      param1 = arcpy.Parameter(displayName = "Pick Join Fields:",
                                                      name = "in_fields",
                                                      datatype= "GPString",
                                                      parameterType= "Required",
                                                      direction= "Input",
                                                       multiValue=True)
      param1.filter.type = "ValueList"
      param1.filter.list = pickTableFieldsList
      parameters = [param0,param1]
      return parameters

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

        #When the 0th parameter gets a value the field headers (1st column in text file) are available to select
        if parameters[0].value:
            joinTable = os.path.join(r"---Folder Containing ACS Text Files Here", parameters[0].valueAsText + ".txt")
            pickedTable = open(joinTable,"r")
            pickedTableFieldsString = pickedTable.readline()
            pickedTableFieldsString = pickedTableFieldsString.replace("\n","")
            pickedTable.close()
            pickedTableFieldsList = pickedTableFieldsString.split(",")
            parameters[1].filter.list = pickedTableFieldsList
        return

View solution in original post

8 Replies
DanPatterson_Retired
MVP Emeritus

Mary, you might want to slide this a bit deeper into the Developer Space to pickup the Python place

GeoNet Community Structure

Python 

0 Kudos
WesMiller
Regular Contributor III

Dan Patterson​ you had(a long time ago) the best example for linking python scripts to a tool box that had a well documented script and a tool box. Do you still have it, would be willing to share again?

0 Kudos
DanPatterson_Retired
MVP Emeritus

Wes Miller    On the iThingy and not able to access my desktop for a while.  The example to which you refer, I am pretty sure was for a conventional toolbox and not one of these python toolboxes (which are often a bit of an overkill most times).  Most of what I see in the script could be substituted with 2 getparametersastext or sys.argvs then define the parameter type, direction, obtained from etc in the tool's properties.

Setting script tool parameters—Help | ArcGIS for Desktop

MaryM
by
Occasional Contributor

I could easily set this task up in a script tool.  Part of this is I am trying to learn how to write a Python Toolbox.  I have not recognized by using the help how to do this correctly.

WesMiller
Regular Contributor III

For python toolbox Defining parameters in a Python toolbox—Help | ArcGIS for Desktop

For script tool

Basically you use in your script someVar = arcpy.GetParameterAsText(0) then set them to correspond in your tool properties.

0 Kudos
MaryM
by
Occasional Contributor

I figured out how to make it work in a Python Toolbox...

import arcpy
import os

class Toolbox(object):
    def __init__(self):
        """Define the toolbox (the name of the toolbox is the name of the
        .pyt file)."""
        self.label = "ACS_2013_5Year_Toolbox"
        self.alias = ""
        # List of tool classes associated with this toolbox
        self.tools = [ACSJoinTableTool]

class ACSJoinTableTool(object):
    def __init__(self):
        """Define the tool (tool name is the name of the class)."""
        self.label = "Join ACS Table to Census Block Group Geometry"
        self.description = "Pick a table to temporarily join to the" + \
                                         "Block Group GIS layer."
        self.canRunInBackground = False

     def getParameterInfo(self):
        """Define parameter definitions"""
        #Make parameter #0 a drop down list of the ACS text files and user can pick one
        filterList = []
        fol = r"---Path of Folder Containing ACS Text Files Here----"
        for i in os.listdir(fol):
            if i.split(".")[-1].find("txt") != -1:
                x = i.split(".")[0]
                filterList.append(x)
        filterList.sort()
      param0 = arcpy.Parameter(displayName = "Pick Table:",
                                                      name = "in_table",
                                                      datatype="GPString",
                                                      parameterType="Required",
                                                      direction="Output")
      param0.filter.list = filterList
    

      #Make parameter #1 filter multi-value check list a of the table columns, the user can check multiple columns
      pickTableFieldsList=[]    
      param1 = arcpy.Parameter(displayName = "Pick Join Fields:",
                                                      name = "in_fields",
                                                      datatype= "GPString",
                                                      parameterType= "Required",
                                                      direction= "Input",
                                                       multiValue=True)
      param1.filter.type = "ValueList"
      param1.filter.list = pickTableFieldsList
      parameters = [param0,param1]
      return parameters

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

        #When the 0th parameter gets a value the field headers (1st column in text file) are available to select
        if parameters[0].value:
            joinTable = os.path.join(r"---Folder Containing ACS Text Files Here", parameters[0].valueAsText + ".txt")
            pickedTable = open(joinTable,"r")
            pickedTableFieldsString = pickedTable.readline()
            pickedTableFieldsString = pickedTableFieldsString.replace("\n","")
            pickedTable.close()
            pickedTableFieldsList = pickedTableFieldsString.split(",")
            parameters[1].filter.list = pickedTableFieldsList
        return

WesMiller
Regular Contributor III

I found this today you may find it useful.

Toolbox to Python Toolbox Wrapper

http://www.arcgis.com/home/item.html?id=83585412edd04ae48bdffea3e1f7b2e7