Spyder and ESRI

From Wildsong
Jump to navigationJump to search

Spyder is an IDE for Python that runs on Windows (and elsewhere). Unlike my favorite IDE Komodo, Spyder does not require admin rights to use it.

See also Portable Windows.

Tips

Lots of useful tips: http://www.southampton.ac.uk/~fangohr/blog/spyder-the-python-ide.html

Setting up the environment

I skirt the issue of which Python runs by using the 32-bit version of miniconda; it can load the 32-bit arcpy module and hence runs ESRI code. If you have the x64 Python modules installed (from ESRI I mean) then you can run 64-bit Python and you have to know in advance which Conda environment to use.

To get around issues of moving between ArcGIS versions (10.2-10.4) when I work on different computers, instead of using project settings in Spyder, I use some python called pystart, which I import at the start of every script.

pystart.py source code

as of 2016-Nov-28

# -*- coding: utf-8 -*-
"""
Created on Sun Sep 11 22:46:00 2016

Change the environment so that ESRI arcpy scripts can run in spyder debugger.
Import this into any script you want to debug in spyder.
Run it standalone to make sure it works on your system.

@author: bwilson
"""
from __future__ import print_function
from glob import glob
import sys, os

def is32bit():
    """ Return True if this python version is 32 bit. """
    return sys.version.find('AMD64')==-1

def find_desktop_folder():
    """ Find the ArcGIS Desktop folder in C:/Programs """
    try:
        latest = sorted(glob('C:\\Program Files (x86)\\ArcGIS\\Desktop10.*'))[-1]
    except:
        print("Could not find ArcGIS Desktop.")
        latest = None
    return latest
    
def find_python_folder():
    """ Find the ArcGIS Desktop Python folder """
    # this needs more testing, but it works at home and at PORE
    pyhome = "C:\\Python2?\\ArcGISx6410*"
    if is32bit(): pyhome = "C:\\Python2?\\ArcGIS10*"
    try:
        latest = sorted(glob(pyhome))[-1]
    except:
        print("Could not find ArcGIS Python.")
        latest = None
    return latest 

# If we're running the wrong version of python the "import arcpy" will fail.
# For example if python is 64-bit and only 32-bit ArcGIS was installed
#if is32bit():
#    print("32 bit python")
#else:
#    print("64 bit python")

desktop_folder = find_desktop_folder()
python_folder = find_python_folder()
if not desktop_folder or not python_folder:
    exit(-1)

python_additions = ['DLLs', 'site-packages']
arcgis_desktop_additions= ['bin', 'arcpy', 'ArcToolbox\\Scripts']
for p in python_additions:
    sys.path.append(os.path.join(python_folder, p))
for p in arcgis_desktop_additions:
    sys.path.append(os.path.join(desktop_folder, p))

if __name__ ==  "__main__":
    import arcpy
    # Now let's try to do something innocuous that tests for a working arcpy
    # Create a table in-memory, add a field, and add a row.
    fc = "a_table"
    cursor = None
    try:
        table = arcpy.CreateTable_management("in_memory", fc)
        arcpy.AddField_management(table, "Field1", "TEXT", field_length=20)
        cursor = arcpy.da.InsertCursor(table, ["Field1"])
        cursor.insertRow(["Hello World"])
    except Exception as e:
        print(e)
    arcpy.Delete_management("in_memory\\"+fc)
    del cursor

Projects in Spyder

Since I don't rely on the PYTHONPATH and instead use pystart.py to set up the path, I generally don't care about Spyder's "projects". I might discover other things that get saved in the project but nothing I need right now.

If you look at the code you will see it's not just changing PYTHONPATH - it has to add the DLL's that ArcPy references to the executable path too. Changing projects settings would not be enough to make ArcPy work.

Sessions

Q. I just noticed "Load session" and "Save session" under File, what do those do?

A. I am guessing it saves and restores what you have entered interactively in the Python console, so that you can persist the history of what you type. I don't use this so I don't care.

Debugger

There are many IDE's for Python on Windows but generally they are either good editors or have a debugger. The commercial ones like Wing and Komodo do both things but require admin privileges to run. (You have to install them.)

With Spyder, you can run or debug a script from inside the IDE.

For running you just click the green arrow. For debugging you can set breakpoints by double clicking the space next to the line number,a red dot will appear. Then you can say "run until you hit a breakpoint" by clicking the "fast forward" arrows.