On Sun, May 5, 2013 at 11:24 PM, Jim Mooney <cybervigila...@gmail.com> wrote: > > I've noticed that if you exit() a program you always get a traceback message: > Traceback (most recent call last): > File "<pyshell#1>", line 1, in <module> > exit('what now?') > File "C:\Python33\lib\site.py", line 380, in __call__ > raise SystemExit(code) > > What if you just want to exit for some normal reason and don't want > the message? Or is a program always supposed to end in some normal way > without an exit. Or is there a different, more graceful way to end a > program when you want?
I believe that traceback is a bug in IDLE, which I think has been fixed for the next release (or is being chased, one of the two). If you're not using IDLE, it's another bug that should be tracked down :). More generally, though, you can't count on 'exit()' being available. exit() is made available by the 'site' module (as you can see in the traceback), but if Python is run with the -S option, 'site' won't be imported and 'exit()' won't be available. Instead, you can do what exit() actually does, which is to raise the SystemExit exception with the code to be returned to the shell. For instance (and be warned that I'm typing this from a Linux box, so it's untested, but you should be able to reproduce this :)): C:\py> type example.py # example.py print('Hello') raise SystemExit(13) print('Goodbye') C:\py> py -3.3 example.py Hello C:\py> echo %ERRORLEVEL% 13 You can also import sys and use sys.exit() for the same effect. If you don't care about the exit code, you can just "drop off" the end of the script. If you don't end with an unhandled exception, your exit code will be 0, otherwise it will (probably) be 1. For example: # example2.py def main(arg=None): print('This is a main function. It's not special, you still have to call it.') if arg: return raise ValueError('If you had supplied an argument, you wouldn't get this message') if __name__ == '__main__': import sys if len(sys.argv) > 1: main(sys.argv[1]) else: main() Hope this helps, Zach Ware _______________________________________________ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor