PythonTemplate

I write a lot of Python code, both for stand-alone scripts and script tools. Over the years, I’ve developed a template that I use for all my Python code. It keeps my code organized and consistent — the first step towards making reusable code.

My template is shown below. Some of the features of this template are:

  • Most-used modules (os, sys, arcpy) are imported
  • Both system and arcpy exceptions are handled
  • Any number of input parameters (arguments) are allowed
  • The statement if __name__ == ‘__main__’:
    evaluates to true whenever the file is run as a stand-alone script or as a geoprocessing script tool. The statement evaluates to false if the file is imported as a module in another Python script — this allows you to use all the functions you defined in the file as a Python module. Essentially, the if __name__ block short circuits the execution of the code in that block unless the Python script it lives in is the one being run.

Here’s my template:

# Copyright:   (c) company name
# ArcGIS Version:   10
# Python Version:   2.6
#--------------------------------
import os
import sys
import arcpy
def do_analysis(*argv):
    """TODO: Add documentation about this function here"""
    try:
        #TODO: Add analysis here
        pass
    except arcpy.ExecuteError:
        print arcpy.GetMessages(2)
    except Exception as e:
        print e.args[0]
# End do_analysis function

# This test allows the script to be used from the operating
# system command prompt (stand-alone), in a Python IDE, 
# as a geoprocessing script tool, or as a module imported in
# another script
if __name__ == '__main__':
    # Arguments are optional
    argv = tuple(arcpy.GetParameterAsText(i)
        for i in range(arcpy.GetArgumentCount()))
    do_analysis(*argv)

Starting from the sample template above, here is a script that merges multiple feature classes from an input workspace using geoprocessing tools.  The “do_analysis” routine is renamed to “merge”:

#-------------------------------------------------------------
# Name:       merge.py
# Purpose:    Merge multiple feature classes from a workspace.
# Author:     esri
# Created:    23/06/2011
# Copyright:   (c) esri
# ArcGIS Version:   10
# Python Version:   2.6
#-------------------------------------------------------------
import os
import sys
import arcpy

def merge(input_workspace, output_feature_class):
    """Merge multiple feature classes from a workspace into a
       new output feature class."""
    try:
        arcpy.env.overwriteOutput = True
        arcpy.env.workspace = input_workspace
        fcs = arcpy.ListFeatureClasses('*')

        # Run merge with the list of feature classes as input
        arcpy.Merge_management(fcs, output_feature_class)

    except arcpy.ExecuteError:
        print arcpy.GetMessages(2)
        arcpy.AddError(arcpy.GetMessages(2))
    except Exception as e:
        print e.args[0]
        arcpy.AddError(e.args[0])

# End main function

if __name__ == '__main__':
    argv = tuple(arcpy.GetParameterAsText(i)
                 for i in range(arcpy.GetArgumentCount())
    merge(*argv)

Several Python IDEs give you an option to specify a template to use anytime you create a new .py file. Here is two examples of Python IDE’s that make creating and using templates easy:

PyScripter

  1. Go to Tools > Options > File templates…
  2. Enter a name
  3. Provide a default extension (i.e. .py)
  4. Enter “Python” for the Category
  5. Enter your Python code in the Template box
  6. Click the Add button

Wingware’s Python IDE

  1. Go to Tools > Templates — a new Template window opens.
  2. In the Template window, right-click and Add new template…
  3. Add the template code in the editor and save.

For a complete list of Python Integrated Development Environments, visit http://wiki.python.org/moin/IntegratedDevelopmentEnvironments

It’s understood no single template can be used to start every project. You may require a library of templates. A template library becomes a go to place for you and your colleagues.

Additional Resources

  • PEP 8 – Style Guide for Python Code – A recommended resource to use when writing Python scripts is the PEP 8 – Style Guide for Python Code. This style guide gives you standard coding conventions to use when writing Python code.
  • PYCH – Online Python Code Checker – This online Python code checker, checks your Python code for errors and pep8 deviations.

This post contributed by Jason Pardy, a product engineer on the Analysis and Geoprocessing team

This entry was posted in Analysis & Geoprocessing and tagged , , , . Bookmark the permalink.

Leave a Reply

9 Comments

  1. nilsbabel says:

    Thanks for the templates. Very helpful. Does PyScripter offer ArcPy code completion?

    Nils

  2. iii_jlhumber says:

    This is a great pattern to follow. Over in our shop we use Komodo IDE (http://www.activestate.com/komodo-ide) which has really nice template capabilities exposed via their Toolbox concept. Code Snippets (aka templates) can include tab stops and linked tab stops — templates really speed things up and improve consistency.

  3. tthor says:

    Thanks; this is a very nice generic template.

    In my coding I’ve followed the example provided by the Spatial Statistics Python script tools; they’re great go-bys. The basic template is very similar to what you have documented, except that a separate function is defined to process the arguments and call the main function whenever __name__ == ‘__main__’. It goes like this:

    # Do your imports…
    # Process passed arguments pass from GUI or cmd line and call main function…
    def setupMainFunction():

    arg1 = arcpy.GetParameterAsText(0)
    arg2 = arcpy.GetParameterAsText(1)
    .
    .
    argn = arcpy.GetParameterAsText(3)

    mainFunction(arg1, arg2, argn)

    # End setupMainFunction

    def mainFunction(arg1, arg2, argn):
    .
    .
    # End mainFunction

    if __name__ == “__main__”:
    setupMainFunction()

    I like the approach used by the Spatial Statistics script tools because it allows you to see, define, and process your arguments as needed up front. It’s not quite as generic, but it is very explicit (which is a good thing for a knucklehead like me).

    Best regards,

    Tracy

  4. uli_schaeffler says:

    There is a bracket missing in the second script.
    In the line before the last line.

    Uli

  5. curtvprice says:

    If anyone was similarly thrown by the cool syntax:

    do_analysis(*argv)

    This unpacks a tuple. The receiving function then just sees the list of arguments, just as if you had used do_analysis(argv(0),argv(1),argv(3)).

    Here’s the python doc on that:

    http://docs.python.org/tutorial/controlflow.html#unpacking-argument-lists

  6. curtvprice says:

    In 9.3 I don’t see a way to find the argument count. Does this mean you need to hard code it?

    if __name__ == "__main__":
      # Get arguments
      numArgs = 6
      argv = tuple([gp.GetParameterAsText(i) for i in range(numArgs)])
      do_analysis(*argv)
    
  7. nbw says:

    @curtvprice

    In 9.3 use the “parametercount” property.

  8. curtvprice says:

    Arc 9.3 help: ParameterCount property

    So:

    if __name__ == “__main__”:
    argv = tuple([gp.GetParameterAsText(i) for i in range(gp.GetParameterCount)])
    MyTool(*argv)

    I’ve been picking up on @tthor’s suggestion:

    def RunMyTool():
    “”"Script tool interface”"”
    argv = tuple([gp.GetParameterAsText(i) for i in range(gp.GetParameterCount)])
    MyTool(*argv)

    def MyTool(arg1=default,arg2,arg3):
    “”"short summary
    … Tool documentation
    “”"
    … script tool code …

    if __name__ == “__main__”:
    RunMyTool()

  9. dshakya says:

    For those who prefer to use Python Tools for Visual Studio in VS environment, I have created a project template and item template for template code above. This gives an ability to create a template from File>New>Python and Add > New item > Python Template

    I will be submitting this to Visual Studio gallery so that it is downloadable/install-able from Extensions menu within Visual Studio.

    For now, you can get it from my OneDrivehttp://1drv.ms/1n7lr19

    Let me know if it works out for you. It supports VS 2012/13 versions. (Express as well)