Dark theme

Arcpy scripts


The second part of the practical is to run arcpy from a script.

Make yourself a directory for this practical. These resources assume it is M:/GEOG5790M/practical2. In there, make a text file external.py. Don't open it in Spyder, just open it in a text editor; Notepad, TextEdit or Notepad++. Add in the following code:

import arcpy

sf = "M:/GEOG5790M/data/input/explosion.shp"
lf = "M:/GEOG5790M/data/generated/explosion.lyr"
lyr = "explosion_lyr" arcpy.management.MakeFeatureLayer(sf, lyr)
arcpy.management.SaveToLayerFile(lyr, lf, "ABSOLUTE")

The first line imports the arcpy module which provides access to ArcGIS functionality.

Next, open a command prompt in the M:/GEOG5790M/practical2 directory (SHIFT + right-click the directory in Windows Explorer -> Open command window here). Alternatively open the command prompt and change to the right drive and then directory.

Run the Python script:

python external.py

This will probably fail with an error. The error message may be along the lines of: 'python' is not recognized...; or,

Traceback (most recent call last):
  File "external.py", line 1, in 
    import arcpy
ModuleNotFoundError: No module named 'arcpy'

If you get the former, then python is a command that is not found on your PATH. If it is the latter, then this means that arcpy isn't installed as a module in the python environment you are using.

What we need to do is use the Python environment installed with ArcGIS. This is probably located as follows: C:\Python27\ArcGIS10.6\python.exe. Once you've found the right Python, run the script thus:

C:\Python27\ArcGIS10.6\python.exe external.py

If you're going to run a lot of these types of script in this way, consider making a shell script or bat file to run them as follows: In the practical2 directory make a text file called p2.bat (not p2.bat.txt) and add the following line:

C:\Python27\ArcGIS10.6\python.exe %1

You should now be able to type the following at the command prompt and it should run the script:

p2 external.py

The %1 means "the first parameter passed to this file" in Microsoft DOS commands, which, in this case is external.py

If you can edit your system or user PATH or put p2.bat somewhere on it, then you should be able to run this from any directory location. If you edit the PATH you will need to restart the command prompt for the changes to be loaded.


If that's worked, you hopefully realise that we can use ArcGIS functionality in external Python programs that are run in this python environment and don't need the user to open up the full ArcGIS system to run things from there. Next we will try to run the tool we developed in the modelbuilder practical , so if you haven't done that, then do that first.


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