Stopping Python addin script

2279
4
05-06-2016 10:06 AM
MikeMacRae
Occasional Contributor III

I am trying to find a way to trap an error in a python addin and stop the script. For example, I want to test if the dataframes spatial reference is a particular coordinate system. If it is not that specific CS, then I want to have a popup messagebox explaing that the user needs to change the CS and then re-run the tool and then have the addin stop running. I've attempted a try/except statement with sys.exit(), however sys.exit() seems to kill ArcMap all together, instead of just stopping the script itself. Is there a better way to accomplish what I want?

try:
    if df.spatialReference.name in ("NAD_1983_BC_Environment_Albers", "NAD 1983 BC Environment Albers"):
           print "No problem with the CS"
    else:
        raise Exception
except Exception:
    pythonaddins.MessageBox("Change dataframe spatial reference to NAD_1983_BC_Environment_Albers and re-run tool", "Report Generator")
    raise sys.exit()
0 Kudos
4 Replies
JakeSkinner
Esri Esteemed Contributor

Hi Mike,

I haven't tested this, but try replacing

raise sys.exit()

with

break

MikeMacRae
Occasional Contributor III

Thanks Jake. I like the break statement. I also think I figured out where I went wrong. I had some code after the try and except statement. I was using sys.exit to try to stop the script, when all I had to do it just move my code into the try portion of the statement instead of outside and then when the exception occured, the script stops without having to use some sort of closing/exit/quit statement. Silly little mistake.

Luke_Pinner
MVP Regular Contributor

Just use `return` to exit the current function

import sys,os
import arcpy
import pythonaddins

class btnThatDoesSomething(object):

    def onClick(self):
        # df = etc...
        
        if df.spatialReference.name not in ("NAD_1983_BC_Environment_Albers", "NAD 1983 BC Environment Albers"): 
            pythonaddins.MessageBox("Change dataframe spatial reference to NAD_1983_BC_Environment_Albers and re-run tool", "Report Generator") 
            return
           
        # Rest of script
AdrianWelsh
MVP Honored Contributor

Break prematurely ends a loop while return passes back a return value to the function caller (basically returns to where the code was previously).