I have an arcpy tool script for ArcGIS 10.0 that has two major functional sections. The user can choose whether or not to run the second section. If the user chooses NOT to run the second section, I simply want to run a cleanup function and exit the script with a sys.exit(0) without having an error message posted to the tool results window. There are two major threads here in GIS-SE about exiting arcpy scripts, but the solutions therein don't specifically address the error message. The general structure of the code is as follows:
import sys
##import arcpy
def CleanUp():
print 'Cleaning up ...\n'
def finish():
CleanUp()
print 'Exiting ...'
sys.exit(0)
do_more = False #or True ... input from user
#Section 1: do some stuff
print 'Doing some stuff ...\n'
if not do_more:
finish()
#Section 2: do more stuff
print 'doing more stuff ...'
CleanUp()
If I run this code in the Python interpreter outside of ArcGIS/arcpy, it works as I'd expect, exiting gracefully with no error message; however, in my arcpy script with this same structure, the script exits, but a SystemExit error message is posted to the tool results window. Is there a way to make the arcpy tool script eat the exception and bury the SystemExit error message?
Answer
Short answer: fixed in 10.1. For now, you're going to need to add an extra level of indentation. This might encourage some useful refactoring to your code though. Any time you get a large number of lines in a single script/routine, you'll want to think about cutting it up into smaller sections (functions, classes) anyway.
def main():
if __name__ == "__main__":
try:
main()
except SystemExit as err:
pass
No comments:
Post a Comment