[Tutor] a graceful program exit

Steven D'Aprano steve at pearwood.info
Thu Aug 12 13:35:01 CEST 2010


On Thu, 12 Aug 2010 04:59:26 pm Chris Fuller wrote:
> The preferred and most graceful way is to use neither, as others have
> pointed out.  However, you can't return an exit code that way

Of course you can. Exiting out the end of the program returns an exit 
code of zero, and raising an uncaught exception returns a non-zero exit 
code:

[steve at sylar ~]$ python -c "pass"
[steve at sylar ~]$ echo $?
0

[steve at sylar ~]$ python -c "raise ValueError('spam')"
Traceback (most recent call last):
  File "<string>", line 1, in <module>
ValueError: spam
[steve at sylar ~]$ echo $?
1


If you need to specify the exit code yourself, and avoid the traceback, 
that's exactly what SystemExit is for:

[steve at sylar babble]$ python -c "raise SystemExit(42)"
[steve at sylar babble]$ echo $?
42


> , and it 
> sometimes isn't feasible to structure your code to allow it.  I
> prefer SystemExit, because it doesn't require adding something to the
> namespace (the sys module), and it seems a bit more pythonic.  You
> can trap it, however, which bugs me.  I think these two should
> exhibit the same behavior.  I'd use sys.exit for "real" code, even
> though it appeals less aesthetically, because it is less prone to
> doing something unexpected (one of Python's guiding principles, btw).

They do have the same behaviour. help(sys.exit) says:

    Exit the interpreter by raising SystemExit(status).

and sure enough, it can be caught:


[steve at sylar ~]$ python -c "
import sys
try:
    sys.exit(42)
except SystemExit:
    print 'Caught'
"
Caught
[steve at sylar ~]$ echo $?
0




-- 
Steven D'Aprano


More information about the Tutor mailing list