AnsweredAssumed Answered

Python script tool function error handling

Question asked by curtvprice Champion on Feb 24, 2015
Latest reply on Mar 12, 2015 by curtvprice

Looking for advice and discussion on implementing script tools.

I have been adopting the convention where my script tools are embedded a functions. Here is my generic template:

 

import os
import sys
import traceback
import arcpy
from arcpy import env

class MsgError(Exception):
    pass

def MyTool(args):
    """Enter python docstring here """
    # init cursor variables
    Row, Rows = [None] * 2
    # init temp file variables
    lyr1,tmp1 = [None] * 2
    try:
        # tool code here
        pass
    except MsgError as xmsg:
        arcpy.AddError(xmsg))
    except arcpy.ExecuteError:
        tbinfo = traceback.format_tb(sys.exc_info()[2])[0]
        arcpy.AddError(tbinfo.strip())
        numMsg = arcpy.GetMessageCount()
        for i in range(0, numMsg):
            arcpy.AddReturnMessage(i)
    except Exception as xmsg:
        tbinfo = traceback.format_tb(sys.exc_info()[2])[0]
        arcpy.AddError(tbinfo + str(xmsg))
    finally:
        # temp files
        for f in [lyr1, tmp1]:
            if f:
                try:
                    arcpy.Delete_management(f)
                except:
                    pass


if __name__ == "__main__":
    # ArcGIS Script tool interface
    # Get arguments, call tool
    argv = tuple(arcpy.GetParameterAsText(i)
        for i in range(arcpy.GetArgumentCount()))
    MyTool(*argv)

 

The issue I'm running into is when I use this tool in another script and import it directly instead of going through ImportToolbox (for performance reasons), for example

 

from rastertools import MyTool
...
MyTool(arg1, arg2)

 

And the tool fails with an error, my calling script does not stop because i handled it. I want my calling script to bail in this situation.

Is the following approach valid? I'm assuming that if MyTool failed I will get a response from arcpy.GetMessages(2) since I called arcpy.AddError() in the called function.

 

MyTool(arg1, arg2)
if arcpy.GetMessages(2):
    raise Exception("Geoprocessing tool MyTool failed")

 

Should I be using ImportToolbox to get my script tool instead of this more direct import of my tool function?

Outcomes