On Thu, Aug 12, 2010 at 6:35 AM, Steven D'Aprano <st...@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: > > [st...@sylar ~]$ python -c "pass" > [st...@sylar ~]$ echo $? > 0 > > [st...@sylar ~]$ python -c "raise ValueError('spam')" > Traceback (most recent call last): > File "<string>", line 1, in <module> > ValueError: spam > [st...@sylar ~]$ echo $? > 1 > > > If you need to specify the exit code yourself, and avoid the traceback, > that's exactly what SystemExit is for: > > [st...@sylar babble]$ python -c "raise SystemExit(42)" > [st...@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: > > > [st...@sylar ~]$ python -c " > import sys > try: > sys.exit(42) > except SystemExit: > print 'Caught' > " > Caught > [st...@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
_______________________________________________ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor