how do I exit gracefully?

Thomas Wouters thomas at xs4all.net
Sun Oct 29 14:37:26 EST 2000


On Sun, Oct 29, 2000 at 04:55:46PM +0000, Andrew Pierce wrote:
> in article mailman.972837503.8498.python-list at python.org, Thomas Wouters at
> thomas at xs4all.net wrote on 10/29/00 11:36 AM:
> > Actually, sys.exit() does raise an exception, but that's besides the point
> > ;) My bet is the exception the original guy was talking about was
> > 'NameError'. He probably forgot to import sys and/or os before using them.
> 
> Uh no.  I did remember to import sys and/or os. :)  The point is I didn't
> want to clutter error logs with sys.exit() calls.  The solution of:
> 
> try:
>     main()
> except SystemExit:
>     #we're ok
> except:
>     #error processing here

> Looks good to me.  I still don't know what (if anything) python does at the
> "normal" program termination of running out of instructions to execute. :/

Ahh, like that. Well, that can never happen: if you are inside the try:,
there is always still code to execute :) And if you are outside the try,
it's irrelevant whether a SystemExit exception was raised, or the
interpreter just stops. (The interpreter does just stop, since it's useless
to raise that exception, but that's besides the point.)

If you run out of code in a function, it will silently return None. If you
run out of a try/except without raising an exception, it will run the 'else'
or 'finally' block, if any, and then continue past the 'try' statement.

If you use os._exit(), you're taking the dirty route out. No exception is
raised, no cleanup is done, and the interpreter just exits. In general,
don't use it, unless you know what you're doing, and you really need it.
(For instance, you are a database driver, and you encountered an internal
inconcistency. You do not want to write your pending, possibly bad and
harmful, data to the database in that case, but you might want to do it if
the exception was, for instance, KeyboardInterrupt (^C).

-- 
Thomas Wouters <thomas at xs4all.net>

Hi! I'm a .signature virus! copy me into your .signature file to help me spread!




More information about the Python-list mailing list