11

I've got a Python script for ArcGIS that I'm working on, and I'd like to have the ability to have the script quit if it doesn't have the necessary data available. I tried a straight up sys.exit() but that would give an exception in ArcMap that I'd like to avoid. I found This thread that suggests using a try block, so I made this function:

def quit_script(message):
log_msg(message) # already defined; writes a message to a file
if log_loc:
 output.close() # close the file used with log_msg()
try:
 sys.exit()
except SystemExit:
 pass

Unfortunately, that didn't work either. Well, it doesn't make that error on ArcMap anymore, but it also doesn't, well, quit. Right now, I have the bulk of my code in an if/else statement, but that's ugly. Anybody have any other suggestions?

Thanks! Brian

asked Apr 22, 2011 at 1:37
3
  • In theory sys.exit(0) is an operation completed successfully exit - see msdn.microsoft.com/en-us/library/ms681381.aspx - but like Michael I'm not near ArcGIS so I couldn't tell you how it's handled. Commented Apr 22, 2011 at 4:13
  • Have you tried raise systemexit? I have a python program I wrote where I use this approach in an if statement by trying to get a list of the features in a workspace, and if it returns an empty list the else calls raise systemexit (works great - I do have lots of log file output and printing going on too so I can tell why the program exited). Probably multiple ways to do this and maybe even better ways, but this one does what I expected/wanted it to do. Commented Apr 22, 2011 at 11:03
  • 4
    Did you see the examples in this GSE thread gis.stackexchange.com/questions/1015/… Commented Apr 22, 2011 at 11:50

1 Answer 1

3

No, the try/except block you will want do have the 'catch' get your exit call; so in your try you would do something like this:

try:
 if arcpy.Exists(parcelOutput):
 arcpy.AddMessage("Calculating Parcel Numbers") 
except:
 raise sys.exit("Error: " + arcpy.GetMessages(x))

This will file if your 'if' statement fails.

Mike T
42.7k10 gold badges131 silver badges194 bronze badges
answered Apr 24, 2011 at 1:58
1
  • I thought except only runs when there is an error to catch? Commented Sep 11, 2016 at 20:17

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.