17

I have tried sys.exit, but it doesn't seem to work in ArcMap 10.

Anyone know how to do it?

PolyGeo
65.5k29 gold badges115 silver badges350 bronze badges
asked Aug 9, 2010 at 20:37

1 Answer 1

16

From ArcPy examples, it seems like sys.exit() is the correct way to terminate a script early.

The Python documentation notes that sys.exit():

is implemented by raising the SystemExit exception, so cleanup actions specified by finally clauses of try statements are honored, and it is possible to intercept the exit attempt at an outer level.

The easy way to deal with this is to wrap your script in an exception handler:

import sys
import arcpy
try:
 #do stuff
 sys.exit(0)
except SystemExit:
 pass

However, this is not particularly elegant and requires a restructure of your entire project, not to mention another level of indentation. Plus, in the unlikely situation that another part of your code raises a SystemExit exception you would never know about it... Another inelegant but perhaps preferable solution is to wrap calls to sys.exit() in another function:

import sys
import arcpy
def finish(arg=None):
 try:
 sys.exit(arg)
 except SystemExit:
 pass
#do stuff
finish()

Now you can call finish(), finish(1), or finish('Error message') just like you expect to be able to call sys.exit().

Of course, we might want to use our exception eating approach in other circumstances, and because this is Python, we can generalise and make a useful, multipurpose decorator:

import sys
import arcpy
def eat_exception(fn, exception):
 def safe(*v, **k):
 try:
 fn(*v, **k)
 except exception:
 pass
 return safe
finish = eat_exception(sys.exit, SystemExit)
#do stuff
finish()
answered Aug 9, 2010 at 23:55

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.