The ArcGIS Model Builder To Python Connection
In Review
ArcGIS allows you to obtain Python code for a Model Builder model. For simple models this can be a good method to convert models to Python and to learn how to call additional ArcGIS functions from Python. However, as models become more complex, the Python code that ArcGIS produces becomes more and more complex they will still need to be rewritten to a large extent. You'll quickly find that it is easier to write scripts from scratch yourself.
1. Create a simple model in Model Builder in ArcGIS
- Create a simple model by opening model builder , adding a data set, adding a single transform, and setting the transform output to a new file.
- Run the model to make sure it is working.
2. Export and examine the Python script
- Within the model builder window select Model -> Export -> To Python Script...
- Give the script an appropriate name making sure it ends in ".py" for "Python"
- Open the script in the Wing IDE or note pad.
- The script should look something like the following:
# ---------------------------------------------------------------------------
# BufferShapefile.py
# Created on: 2011-07-09 15:44:17.00000
# (generated by ArcGIS/ModelBuilder)
# Description:
# ---------------------------------------------------------------------------# Import arcpy module
import arcpy
# Local variables:
Colorado_shp = "C:\\Colorado.shp"
test123_shp = "C:\\test123.shp"# Process: Buffer
arcpy.Buffer_analysis(Colorado_shp, test123_shp, "1 Unknown", "FULL", "ROUND", "NONE", "")
The script starts with a simple header block for the file with the file name, the date it was created and an empty description. Then the script "imports" the "arcpy" library. This is the primary library you'll be using to access ArcGIS from Python.
The script then sets up some local variables for parameters to the buffer function. Notice the double slashes on the file paths. These are required in file name as a single slash is a special character you'll hear more about later. Lastly there is the call to the "Buffer_analysis" function. Notice the names of the input and output files and then the other parameters being sent to the function. They are all in quotes making them into strings.
This has been a very fast introduction to ArcGIS and Python scripting. We are now going to shift gears to just learning the Python scripting language because learning Python and ArcGIS's Python functions at the same time is just too much!