The following tutorial develops some basics for using the Arcpy library with Python.
1. Every script using Arc functions must start with import arcpy
'''script.py ''' import arcpy
2. Get user inputs with ‘GetParameterAsText’
'''script.py ''' import arcpy # get input feature class inputFeatureClass = arcpy.GetParameterAsText(0)
This gets the first user entered parameter as text. If you haven’t specified any parameters when adding to Arc (see step 3) it will cause the script to fail.
3. Using the tool in Arc
Right click on a toolbox you can edit (if you haven’t already, you will have to create one in “My Toolboxes” or within a folder), go down to ‘Add’ and select ‘Script…’, give it a name and label, select the script file, then add the parameters. For this example we are getting a Feature Class, so call it InputFeatureClass (or something meaningful) and set the Data Type to Feature Class. Click Finish. Double click on your new script tool to use it. At the moment it does nothing, but if you give it a feature class and click OK, it should run happily and say it was successful.
From now on we can just edit the script where it is and the changes will carry through, you won’t need to import it again.
It is important to note that paths to feature classes are just strings, e.g. ‘C:\\GISData\\NYC\\2007\\Networks.gdb\\BusRoutes’.
4. Adding messages to the display with ‘AddMessage’
'''script.py ''' import arcpy # get input feature class inputFeatureClass = arcpy.GetParameterAsText(0) # inform user of selected feature class path arcpy.AddMessage(' Input Feature Class: '+inputFeatureClass)
Save the script and run it again, and it will now print the feature class path before finishing.
5. Performing a geoprocessing operation
Let’s do a buffer on the input features, and also get the user to input the buffer size for the operation; you will need to right click on the tool in Arc, go down to Properties, and in the parameters tab add the parameter BufferSize_m as a Long (integer).
Buffer also requires an output feature class, so you will have to add that to the parameters as well; its data type should be feature class, but you will need to set the Direction (under Parameter Properties) to Output.
The script now becomes (with the message made a little more meaningful):
'''script.py ''' import arcpy # get input feature class inputFeatureClass = arcpy.GetParameterAsText(0) # get buffer size buffer = arcpy.GetParameterAsText(1) # get output feature class outputFeatureClass = arcpy.GetParameterAsText(2) # inform user of selected feature class path arcpy.AddMessage(' Buffering input Feature Class, '+inputFeatureClass+' by '+buffer+' Meters and writing to: '+outputFeatureClass) buffer_corrected = buffer + ' Meters' arcpy.Buffer_analysis(inputFeatureClass, outputFeatureClass, buffer_corrected)
This should help you get started…
- do some Pyhton tutorials, and
- constantly refer to the documentation (either in Arc, or on the ESRI website)