How do you exit python during execution of script?

Tim Peters tim_one at email.msn.com
Mon Sep 13 20:49:52 EDT 1999


[H. P. Friedrichs]
> Why does this generate an exception?
>
> import sys
> try:
>     print "normal operation"
>     sys.exit()        # I want to leave the script here
> except:
>     print "something went wrong"
>     sys.exit()        # instead, I dump out here...why?

D:\Python>python
Python 1.5.2 (#0, Apr 13 1999, 10:51:12) [MSC 32 bit (Intel)] on win32
Copyright 1991-1995 Stichting Mathematisch Centrum, Amsterdam
>>> import sys
>>> print sys.exit.__doc__
exit([status])

Exit the interpreter by raising SystemExit(status).
If the status is omitted or None, it defaults to zero (i.e., success).
If the status numeric, it will be used as the system exit status.
If it is another kind of object, it will be printed and the system
exit status will be one (i.e., failure).
>>>

Raising SystemExit gives outer code blocks a chance to do cleanup on the way
out.  Screwing outer blocks is anti-social, not to mention stupid.  Which is
why os._exit() also exists.

python-doesn't-force-you-to-play-nice-but-when-it-makes-you-use-an-
    underscore-it-wants-you-to-feel-guilty-ly y'rs  - tim






More information about the Python-list mailing list