Saving, loading, and recalling your work in the Python window

Saving your work

The Python window provides a location to learn about and experiment with Python in an ArcGIS for Desktop application. In many cases, it may be useful to save work done in the Python window to a file that can be referenced or used in later sessions.

The contents of the Python window can be saved to a Python file or text file. Right-click the Python window and select Save As to save your code either as a Python file (.py) or Text file (.txt). If saving to a Python file, only the Python code will be saved. If saving to a Text file, everything shown in the Python window, including the Python code, returned messages, and the command prompt (>>>), will be saved to the output file.

Python window Save As

When saving code from the Python window, only the content that is currently in the Python window will be exported to the output file. Content that has been cleared or deleted will not be part of the saved file.

Loading Python into the Python window

The Python window is an interactive Python interpreter that is useful for quick execution of geoprocessing tools or other Python commands. However, code that has already been written and saved to a stand-alone script or Python file can also be loaded into the Python window, modified, and executed. Below is a simple script that looks at a feature class and field and produces a unique list of field values. The sample is simple enough, but entering all 13 lines manually into the Python window would take considerable time. Instead, by right-clicking in the Python window and selecting Load, this code (contained in a stand-alone script or Python file) is immediately loaded into the Python window. Once loaded into the Python window, edits can be made to the feature class location, field name, or syntax, and the code can be executed by hitting the ENTER key with the cursor at the last line of code.

Creates a unique list of field values based on a feature class and field name

import arcpy
featureclass = "C:/data/county.gdb/hospital"
field = "Zip"

valueList = []
rows = arcpy.da.SearchCursor(featureclass, [field])
for row in rows:
    valueList.append(row[0])

uniqueSet = set(valueList)
uniqueList = list(uniqueSet)
uniqueList.sort()

print(uniqueList)

Recalling Python code

Lines of code executed in previous lines can be recalled using the up and down arrow keys. This recall inserts the specified line at the current command prompt location. The line of code can be edited and executed or run as-is a second time.

4/16/2013