[Tutor] exit message
Steven D'Aprano
steve at pearwood.info
Mon May 6 11:05:12 CEST 2013
On Sun, May 05, 2013 at 09:24:30PM -0700, Jim Mooney wrote:
> I've noticed that if you exit() a program you always get a traceback message:
Which exit are you talking about? There is sys.exit, and there is also
the interactive exit() function defined by the site module for
interactive use.
> 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?
The normal way to exit a program is to just "fall out the bottom" when
you reach the end. Once all loops are ended, and you reach the end of
code, Python just neatly exits with no error.
Another alternative is to call sys.exit(), either with no argument, or
an argument of 0. The convention for command-line tools is that an exit
value of 0 means "no problem, the application ended normally". If you
pass any other value, Python will generate a non-zero exit code for you.
A third way is to call down fire from the heavens and bring about the
apocolypse for your program by calling os._exit(), which literally kills
the application dead without giving it a chance to clean up after
itself, close files, etc. Don't use this unless you know what you're
doing. It also takes a status code argument like sys.exit.
Last but not least, if you raise SystemExit (or for that matter any
exception) which is not caught by a try...except block, Python will exit
your program with a non-zero exit code.
As always, IDLE may play silly tricks. You should not run programs "for
real" under IDLE, but only while you are actively writing code, testing,
etc. That's why IDLE is called an Interactive Development Environment --
if you're not interactively developing, don't use it.
(Actually, I am a great believer in not using IDLE for anything. If your
application acts weird, is that because it has a bug, or because IDLE is
doing something "clever"? I much prefer a text editor and a terminal
window. But then I'm spoilt because I use Linux, where the standard
environment is practically an IDE on its own.)
--
Steven
More information about the Tutor
mailing list