[Tutor] a graceful program exit
Bill Allen
wallenpb at gmail.com
Thu Aug 12 19:31:09 CEST 2010
On Thu, Aug 12, 2010 at 6:35 AM, Steven D'Aprano <steve at pearwood.info>wrote:
> 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,
Excellent! I think that may be everything I needed to know about that. I
appreciate you and the others responding.
Thanks,
Bill Allen
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100812/4f0ccf51/attachment-0001.html>
More information about the Tutor
mailing list