How To: Repeat run a model by calling the model from a Python script and passing arguments to it
This article provides a procedure to repeat run a model by calling the model from Python within a loop and pass arguments to it. It is one of two methods available to create batch style processes so that geoprocessing models can be repeated.
Another method of batching geoprocessing tasks is to create a model of the basic task, export that to a script and then add Python code to perform looping. See the link in the Related Information section for more information on this method.
While the geoprocessing environment of ArcGIS 9.x supports Python, VBScript, JScript, and Perl scripting languages,any scripting language that is COM compliant can be used to create successful geoprocessing scripts.
While tracing through the script below there are a number of important things to note.
· First, the script sets the workspace property of the geoprocessor object to a path. This tells the geoprocessor object that all data can be found in this location unless otherwise stated.
· The script then calls the ListFeatureClasses method, which returns a list of all the feature classes in the workspace. This list can be stepped through and various operations applied to the contents of the list. To step through the list, the script uses the '.next' method of the list in conjunction with a 'while' loop. The while loop says, "While the position in the feature class list (fc) contains something, execute the lines of code in the loop".
· The code demonstrates the simple formula for performing batch operations: get a list of the objects to which to apply operations, and use a while loop to iterate over this list.
The code example below uses the example model called 'MyClipTool'. It resides in a toolbox called 'MyToolbox'. MyClipTool has two arguments: an input shapefile and an output shapefile. The script loops through each file in 'C:\mydata\input_folder\'. For each iteration of the loop, it executes MyClipTool passing in an input shapefile and writing the output to 'C:\mydata\output_folder\'.
# Import system modules
import sys, string, os, win32com.client
# Create the Geoprocessor object
gp = win32com.client.Dispatch("esriGeoprocessing.GpDispatch.1")
# Load required toolboxes...
gp.overwriteoutput = 1
gp.workspace = "C:\\mydata\\input_folder\\"
outfolder = "C:\\mydata\\output_folder\\"
fcs = gp.ListFeatureClasses()
fc = fcs.Next()
gp.MyClipTool(fc, outfolder + fc)
fc = fcs.Next()
For more information on getting started with writing geoprocessing scripts, see the 'Writing Geoprocessing Scripts' white paper. It is available on the ESRI Library CD and is entitled Writing_Geoprocessing_Scripts.pdf.
- Use scripting in ArcGIS Desktop to run custom tools and repetitive geoprocessing workflows and tasks