Python script tool function error handling

4528
2
02-24-2015 03:16 PM
curtvprice
MVP Esteemed Contributor

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?

0 Kudos
2 Replies
curtvprice
MVP Esteemed Contributor

No response.... any ideas? Should I always import tools using arcpy.ImportToolbox to properly handle tool failure? I think I was avoiding this in the past before tools ran in process.

0 Kudos
SarahSchwarzer1
New Contributor II

I was so excited because this is finally the question that should get the answer I need. I want my tool to stop right where it is, but it keeps going past the error. Maybe 6 years later someone will answer?

0 Kudos