Dark theme

Arcpy scripts


So, we've seen we can run standard ArcGIS components from the ArcGIS python environment. The third part of the practical is to run our bespoke model from an external script.

In order to run our bespoke tool, we need to import our custom toolbox, which we called "Models" in the last practical. We'll also need to set the workspace. We can then invoke the model, which we called "Explosion":

import arcpy

arcpy.env.workspace = "m:/GEOG5790M/practical1"
arcpy.ImportToolbox("m:/GEOG5790M/practical1/Models.tbx", "models")
arcpy.Explosion_models(...) # Won't work at the moment

However, before this will work, we need to fill in the parameters. The simplest way to find out what these should be is to run the model inside ArcGIS. The message dialog starts by saying what the parameters are. For example, mine says:

Executing: Explosion "100 Meters" M:\GEOG5790\data\input\explosion.shp M:\GEOG5790\data\input\buildings.lyr M:\GEOG5790\data\output\result.shp
Start Time: Sun Feb 04 15:40:09 2018...[etc.]

You can pretty much cut and paste these into the script, however, a few changes are needed:

  1. The parameters need separating with commas.
  2. The file addresses need to be in double quotes.
  3. The output files need to be new ones or you need to delete the ones that are there.

Give it a go and try to get your model to work.


Once you have that running, let's add one extra thing, which is a try-except block. This will help us diagnose what is wrong if something does go wrong as we develop something more sophisticated later:

import arcpy

try:
    try:
        arcpy.ImportToolbox("m:/GEOG5790M/practical1/Models.tbx", "models")
    except arcpy.ExecuteError as e:
        print("Import toolbox error", e)
    try:
        arcpy.Explosion_models(...) # Your parameters, here.
    except arcpy.ExecuteError as e:
        print("Model run error", e)
except Exception as e:
    print(e)

Note carefully that we've isolated each potentially tricky bit of code in separate exception captures, but also encompassed everything with a catch-all. If you run the code a couple of times (so it breaks trying to overwrite the files), you'll see the difference between this and the default behaviour (assuming you tried that too).

If the output shapefiles already exist, you may have to delete them first using ArcCatalog or add code to delete them first if they exist.


Now lets move our script into our ArcToolbox and run it from there.



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