I have created a script (see below) that works ok but only in case if all parameters are required inputs. Quite simple, Roads(line) and Trackts(polygon) feature classes , first buffer Roads and then clip to Tracts. There are more feature classes in Zion.gdb but I am just doing a test script to figure out optional input parameters.
What I need is that user should be able to select the layer they want to buffer, the layer they want to clip, the output location/name of the clip, and the buffer distance. All of it has to be optional. The problem is when I set for example Tracts and Tracts_Clip feature classes to optional in Script Parameters and do not apply them in script execution because I want only Roads buffer, the script does not work.
enter image description here enter image description here
import arcpy
from arcpy import env
# set environment settings
env.workspace = "C:/data/Zion.gdb"
env.overwriteOutput = True
# Script arguments
Roads = arcpy.GetParameterAsText(0)
if Roads == '#' or not Roads:
Roads = arcpy.GetParameterAsText(0) # provide a default value if unspecified
Tracts = arcpy.GetParameterAsText(1)
if Tracts == '#' or not Tracts:
Tracts = arcpy.GetParameterAsText(1) # provide a default value if unspecified
Tracts_Clip = arcpy.GetParameterAsText(2)
if Tracts_Clip == '#' or not Tracts_Clip:
Tracts_Clip = arcpy.GetParameterAsText(2) # provide a default value if unspecified
Buffer_Distance = arcpy.GetParameterAsText(3)
if Buffer_Distance == '#' or not Buffer_Distance:
Buffer_Distance = arcpy.GetParameterAsText(3) # provide a default value if unspecified
# Local variables:
Tracts_Clip = arcpy.GetParameterAsText(2)
Buffer_Distance = arcpy.GetParameterAsText(3)
Roads_Buffer = "Roads_Buffer"
# Process: Buffer
arcpy.Buffer_analysis(Roads, Roads_Buffer, Buffer_Distance,"FULL", "ROUND", "ALL", "", "")
# Process: Clip (1)
arcpy.Clip_analysis(Tracts, Roads_Buffer, Tracts_Clip, "")
-
you can est your defaults in the parameter tab of the tool properties, rather than needing to do it in the script.Adam– Adam2017年03月13日 22:53:44 +00:00Commented Mar 13, 2017 at 22:53
1 Answer 1
You can build a simple logic testing whether user has provided any value for each of parameters:
import arcpy
Roads = arcpy.GetParameterAsText(0)
Tracts = arcpy.GetParameterAsText(1)
roads_def = 'path to feature class'
tracts_def = 'path to feature class'
if Roads:
arcpy.AddMessage(Roads)
else:
arcpy.AddMessage('No parameter1 value; using {}'.format(roads_def))
Roads = roads_def
if Tracts:
arcpy.AddMessage(Tracts)
else:
arcpy.AddMessage('No parameter2 value; using {}'.format(tracts_def))
Tracts = tracts_def
Alternatively, you could use
ToolValidator
class to update parameters values after user has provided a value for one or more other parameters;- Use default value associated with each of the parameters that user will see when starting the tool.