Script in ArcToolbox:Inspect table/fc/input1 for fields to be used in input2

271
1
11-23-2010 06:54 AM
justinperez
New Contributor II
Glad to be using the new python subforum!

I want to have my python script look at the fields (gp.listfields maybe) and create a dropdown input box for the user to be able to see that the script can see what fields are in the input1.

Use case is I want to get a list of unique values in a field.  I know I can have the user open the table/fc and discover the field and then type it into an input box but that isn't cool.  I imagine it will have to be a two part script..like do a gp.listfields then ask the user to pick the field then start running again.  Here is my code now.

import os, string, sys, win32gui
import arcgisscripting
gp = arcgisscripting.create(9.3)
gp.workspace = "c:\\"

infc = sys.argv[1]
field = sys.argv[2]

for fld in gp.listfields(infc):
    pass
    #stuck here!
   

try:
    rowlist = []###unique values in user specified column
    sc = gp.searchcursor(infc)#user defined
    row = sc.next()
    while row:
        altline = row.getvalue(field)#user defined
        #print altline
        if str(altline) not in rowlist:
            rowlist.append(str(altline))
        row = sc.next()
    del row
    del altline

except:
    print gp.getmessages()
Tags (2)
0 Kudos
1 Reply
ChrisSnyder
Regular Contributor III
This is v9.3 code, but I think it does the same thing as your code.
P.S. I use this thing all the time to for SQL - it's very handy!!!

# Name: list_selected_values_v93.py
#
# Description
# -----------
# This script will list the unique values of selected features/records in a FC or table
# in a specified sort order. I meant this tool to be used to format long text strings
# as value1, value2, value3, etc. so that I could use it as part of an SQL expression.
#
# Written By: Chris Snyder, WA DNR, chris.snyder(at)wadnr.gov
#
# Written For: Python 2.5.1 and ArcGIS v9.3.1 SP1
#
# UPDATES:
#
# Notes on input parameters (for the toolbox):
# VARIABLE             PAREMETER_INDEX     PARAMETER_DATA_TYPE
# -------------------------------------------------------------------
# inputLayer           0                   TableView (the input FeatureClass, Table, FeatureLayer or TableView)
# inputFieldName       1                   Field Name
# inputSortOrder       2                   String ("ASCENDING","DESCENDING", "UNSORTED")
#

try:
    #Process: Import some modules
    import os, string, sys, time, traceback, arcgisscripting

    #Process: Create the gp object
    gp = arcgisscripting.create(9.3)

    #Process: Defines some functions used for getting messages from the gp and python
    def showGpMessage():
        gp.AddMessage(gp.GetMessages())
        print >> open(logFile, 'a'), gp.GetMessages()
        print gp.GetMessages()
    def showGpWarning():
        gp.AddWarning(gp.GetMessages())
        print >> open(logFile, 'a'), gp.GetMessages()
        print gp.GetMessages()
    def showGpError():
        gp.AddError(gp.GetMessages())
        print >> open(logFile, 'a'), gp.GetMessages()
        print gp.GetMessages()
    def showPyLog(): #just print to the log file!
        print >> open(logFile, 'a'), str(time.ctime()) + " - " + message
    def showPyMessage():
        gp.AddMessage(str(time.ctime()) + " - " + message)
        print >> open(logFile, 'a'), str(time.ctime()) + " - " + message
        print str(time.ctime()) + " - " + message
    def showPyWarning():
        gp.AddWarning(str(time.ctime()) + " - " + message)
        print >> open(logFile, 'a'), str(time.ctime()) + " - " + message
        print str(time.ctime()) + " - " + message
    def showPyError():
        gp.AddError(str(time.ctime()) + " - " + message)
        print >> open(logFile, 'a'), str(time.ctime()) + " - " + message
        print str(time.ctime()) + " - " + message

    #Specifies the root directory variable, defines the logFile variable, and does some minor error checking...
    dateTimeString = str(time.strftime('%Y%m%d%H%M%S'))
    scriptName = os.path.split(sys.argv[0])[-1].split(".")[0]
    userName = string.lower(os.environ.get("USERNAME")).replace(" ","_").replace(".","_")
    tempPathDir = os.environ["TEMP"]
    logFileDirectory = r"\\snarf\am\div_lm\ds\gis\tools\log_files"
    if os.path.exists(logFileDirectory) == True:
        logFile = os.path.join(logFileDirectory, scriptName + "_" + userName + "_" + dateTimeString + ".txt")
        try:
            print >> open(logFile, 'a'), "Write test successfull!"
        except:
            logFile = os.path.join(tempPathDir, scriptName + "_" + userName + "_" + dateTimeString + ".txt")  
    else:
        logFile = os.path.join(tempPathDir, scriptName + "_" + userName + "_" + dateTimeString + ".txt")
    if os.path.exists(logFile)== True:
        os.remove(logFile)
        message = "Created log file " + logFile; showPyMessage()
    message = "Running " + sys.argv[0]; showPyMessage()
    
    #Process: Check out the highest license available
    try:
        if gp.CheckProduct("ArcView") == "Available":
            gp.SetProduct("ArcView")
        elif gp.CheckProduct("ArcEditor") == "Available":
            gp.SetProduct("ArcEditor")
        elif gp.CheckProduct("ArcInfo") == "Available":
            gp.SetProduct("ArcInfo")
    except:
        message = "ERROR: Could not select an ArcGIS license level! Exiting script..."; showPyError(); sys.exit()
    message =  "Selected an " + gp.ProductInfo() + " license"; showPyMessage()

    #Process: Sets some gp environment variables
    gp.overwriteoutput = True

    #Process: Collect the input parameters
    inputLayer = gp.GetParameterAsText(0) #tableview
    inputFieldName = gp.GetParameterAsText(1) #fieldname
    inputSortOrder = gp.GetParameterAsText(2) #string

    #Process: Print out the input parameters
    message = "INPUT PARAMETERS"; showPyMessage()
    message = "----------------"; showPyMessage()
    message = "Input Layer              = " + inputLayer; showPyMessage()
    message = "Input Field Name         = " + inputFieldName; showPyMessage()
    message = "Sort Order               = " + inputSortOrder + "\n"; showPyMessage()
    
    #Some error checking:
    try:
        dsc = gp.describe(inputLayer)
    except:
        message = "ERROR: Could not describe input layer! Exiting script..."; showPyError(); sys.exit()
    #make sure the inputLayer is a FeatureClass or Table
    inputLayerDataType = dsc.datasettype
    if inputLayerDataType not in ("FeatureClass","Table"):
        message = "ERROR: Input layer type (" + str(inputLayerDataType) + ") is not a FeatureClass or Table! Exiting script.."; showPyError(); sys.exit()
    #make sure inputFieldName is in inputLayer
    if len(gp.listfields(inputLayer, inputFieldName)) == []:
        message = "ERROR: Input layer does not contain a " + str(inputFieldName) + " field! Exiting script..."; showPyError(); sys.exit()
    #Make sure a valid sort method is being provided
    if inputSortOrder not in ("ASCENDING","DESCENDING","UNSORTED"):
        message = "ERROR: Input sort order must be either ASCENDING, DESCENDING, or UNSORTED! Exiting script..."; showPyError(); sys.exit()
    elif inputSortOrder == "ASCENDING":
        fieldSortString = inputFieldName + " A"
    elif inputSortOrder == "DESCENDING":
        fieldSortString = inputFieldName + " D"
    else:
        fieldSortString = ""
    #Determine the field type of inputFieldName
    try:
        inputFieldNameType = gp.listfields(inputLayer, inputFieldName)[0].type
    except:
        message = "ERROR: Could not determine the field type of the specified Input Field Name! Exiting script..."; showPyError(); sys.exit()
    
    #Process: Create a string to return
    uniqueValueList = []
    uniqueValueCount = 0
    searchRows = gp.searchcursor(inputLayer, "", "", "", fieldSortString)
    searchRow = searchRows.next()
    while searchRow:
        fieldValue = searchRow.getvalue(inputFieldName)
        if fieldValue not in uniqueValueList:
            uniqueValueCount = uniqueValueCount + 1
            uniqueValueList.append(fieldValue)
        searchRow = searchRows.next()
    del searchRow
    del searchRows
    uniqueValueString = ""
    for uniqueValue in uniqueValueList:
        if inputFieldNameType in ("String","Text"):
            uniqueValueString = uniqueValueString + "'" + str(uniqueValue) + "',"
        else:
            uniqueValueString = uniqueValueString + str(uniqueValue) + ","
    message = "UNIQUE VALUES: " + str(uniqueValueString[:-1]); showPyMessage()
    message = ""; showPyMessage()
    message = "BTW: There are " + str(uniqueValueCount) + " unique values!"; showPyMessage()
    
except:
    message = "\n*** PYTHON ERRORS *** "; showPyMessage()
    message = "Python Traceback Info: " + traceback.format_tb(sys.exc_info()[2])[0]; showPyMessage()
    message = "Python Error Info: " +  str(sys.exc_type)+ ": " + str(sys.exc_value) + "\n"; showPyMessage()
0 Kudos