2

I have a script that creates a new feature using arcpy.GetParameterAsText, but I'm having trouble creating an error message for incorrect user input. The input for a parcel # should be something like '1500300000029', but what if 'sdfjfh' is entered? As it stands no error is thrown and a empty feature is created. I've also tried inside PythonWin by assigning a bad entry for 'input' and it runs without error.

import arcpy
import sys
arcpy.env.overwriteOutput = True
try:
 Parcels = "..path to data"
arcpy.env.workspace = "C:/Data_new/Temp/Default.gdb"
#input = arcpy.GetParameterAsText(0) 
input = "dfdsgdg" 
expression = "PARCEL_ID = " + "'" + str(input) + "'"
arcpy.MakeFeatureLayer_management(Parcels, "parcels_lyr")
arcpy.SelectLayerByAttribute_management("parcels_lyr", "NEW_SELECTION", expression) 
arcpy.CopyFeatures_management("parcels_lyr", "output")
except:
 print arcpy.GetMessages()

I've also tried

except StandardError, ErrDesc:
 arcpy.AddWarning(input)
 arcpy.AddWarning(ErrDesc)
except:
 arcpy.AddWarning(input)
 arcpy.AddWarning(ErrDesc)

What is the appropriate way to handle this?

PolyGeo
65.5k29 gold badges115 silver badges349 bronze badges
asked May 23, 2013 at 12:34
3
  • 2
    I just use GetCount to see whether what is passed in found any features and then act accordingly. You may want to also use Tool Validation. Commented May 23, 2013 at 12:49
  • i altered my code using your advice and it works when I run inside PythonWin, but nothing is presented when ran inside ArcMap. isValid = int(arcpy.GetCount_management("parcels_lyr").getOutput(0)) if isValid < 1: raise ValueError else: arcpy.CopyFeatures_management("parcels_lyr", "output") except ValueError: print "Oops!" Commented May 23, 2013 at 13:27
  • Nevermind....Except: arcpy.AddWarning("Invalid Entry.") did the trick. thanks!! Commented May 23, 2013 at 13:32

1 Answer 1

4

When running something like this in a Toolbox Tool, you indeed want to use Tool Validation. For example:

class ToolValidator:
 """Class for validating a tool's parameter values and controlling
 the behavior of the tool's dialog."""
 def __init__(self):
 """Setup arcpy and the list of tool parameters."""
 import arcpy
 self.params = arcpy.GetParameterInfo()
 def initializeParameters(self):
 """Refine the properties of a tool's parameters. This method is
 called when the tool is opened."""
 return
 def updateParameters(self):
 """Modify the values and properties of parameters before internal
 validation is performed. This method is called whenever a parmater
 has been changed."""
 return
 def updateMessages(self):
 """Modify the messages created by internal validation for each tool
 parameter. This method is called after internal validation."""
 if self.params[0].value:
 is_a_number = self.is_number(self.params[0].value)
 if not is_a_number:
 self.params[0].setErrorMessage("Input is not a number")
 return
 def is_number(self, string_to_test):
 try:
 int(string_to_test)
 return True
 except ValueError:
 return False

When run with a string entered as the input, it gives a error message to the user, prohibiting them from moving on without fixing the problem:

enter image description here

Tool Validators are great, you can use them for testing all kinds of stuff such as the datum or spatial reference of an layer, folder and file names (using regex is you want), or just about anything.

answered May 23, 2013 at 13:47
2
  • Thanks. I'll definitely refer to this in the future. But my input string can include letters as well (1500700000035A) for example, so I couldn't check for only numbers. I thought about checking for correct length, but (1500700000035) is also a valid entry. Commented May 23, 2013 at 14:38
  • 1
    In that case, you probably just want to use a simple regular expression like ^\d*\w$ (untested) to validate the input string. Commented May 23, 2013 at 15:26

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.