how do I exit gracefully?

Andrew Dalke dalke at acm.org
Sat Oct 28 21:22:32 EDT 2000


Thomas A. Bryan wrote:
>sys.exit() should exit the program, not raise an exception.

That is not correct.

>>>> raise ValueError
>Traceback (innermost last):
>  File "<stdin>", line 1, in ?
>ValueError
>>>> import sys
>>>> sys.exit(0)
>$

All that example proves is that the top-level handler doesn't catch the
SystemExit exception.  Consider

>>> import sys
>>> try:
...     sys.exit(12)
... except SystemExit, x:
...     print "Want to exit with value %d?  Sorry." % x[0]
...
Want to exit with value 12?  Sorry.
>>>

Andrew Pierce wrote:
> I dug around the FAQ and DejaNews and found sys.exit() and
> os._exit() but both of these methods raise exceptions.

os._exit should call the C function '_exit' and not raise an exception.
For example, the interpreter dies for me if I do the following.

>>> import os
>>> try:
...  os._exit(0)
... except:
...  print "Caught exception"
...

But I've never needed to use os._exit in any of my code.  Why do you need
it?

> I have a number of checks that need to pass for a cgi-script and if any
> of them fail I'd like a graceful (and preferably silent) way to end the
> script.

Hmm.  Well, I rather dislike silently ignoring failures.  Still, you really
should either use sys.exit(0) or raise a SystemExit(0) exception and not
just stop in the middle of your code.

There may be a problem with some code which wasn't written to be a library.
Consider:
  try:
    x = get_spam()
  except:
    # guess there wasn't spam, so
    x = "eggs"

A better bit of code would pass through KeyboardInterrupt and SystemExit
because both of those are usually handled at the top level of the code.

  try:
    x = get_spam()
  except (KeyboardInterrupt, SystemExit):
    raise
  except:
    x = "eggs"

Better yet would be to define which exceptions are expected from the
get_spam function and only catch and handle those, or pass in a default
value which is used for the failure case, or return a special object
which is used to indicate a failure.

So if your code doesn't blindly catch and ignore SystemExits, then
sys.exit(0) should be exactly what you want.

                    Andrew
                    dalke at acm.org






More information about the Python-list mailing list