Dark theme

Arcpy


This practicals goes through a range of options for running Python in ArcGIS.

First we run some commands from the ArcGIS Python Window, then compile a Python script using ArcPy to access the same functionality from the ArcGIS Python environment. Then we add the Python script to an ArcToolbox and run it from there.

Let's have a go at converting a shapefile into a layer file from the Python Window. The conversion is a two stage process, first we have to make a layer (in memory), then this in memory layer has to be saved to a file. First let us find the names of the tools we are going to use:

Open ArcToolbox and find the Data Management Tools toolbox. Right-click it and select Properties. You should see it has a single word alias management. This is the name we need. Close the properties and expand the toolbox. Find the Layers and Table Views toolset, and expand the list. Right-click the Make Feature Layer tool and select Properties. The Name property should be the single word MakeFeatureLayer. This is the name we need. Close the properties.

In the Layers and Table Views tools right-click Save To Layer File and select Properties. The Name property should be the single word SaveToLayerFile. This is the other name we need. Close the properties.

With ArcPy we have two choices for refering to built in tools programmatically. We can either use the toolbox name like it is a suffix or like it is a module name, thus:

arcpy.management.MakeFeatureLayer()
or
arcpy.MakeFeatureLayer_management()
both do the same job.

In ArcMap, click the Python Window icon:
Screenshot: Python Window icon
Once the window opens, assuming you've still got last practical's input files, type/copy the following two lines into the window and press ENTER (adjust the paths as needed):

arcpy.management.MakeFeatureLayer("M:/GEOG5790M/data/input/explosion.shp", "explosion_lyr")

arcpy.management.SaveToLayer("explosion_lyr", "M:/GEOG5790M/data/generated/explosion.lyr")

It will return an error if the layer file "M:/GEOG5790M/data/generated/explosion.lyr" already exists or if the M:/GEOG5790M/data/generated/ directory does not exist.

To find out what the parameters are for an arcpy command, we can use the documentation on the ESRI website:

(Data Management Toolbox Overview)

Let's now do the same from a script.


  1. This page
  2. Scripting standard tools <-- next
  3. Scripting bespoke tools
  4. Adding to Arc