[Tutor] HOWTO exit

Michael P. Reilly arcege@speakeasy.net
Sun, 22 Jul 2001 15:17:37 -0400 (EDT)


Adam Seyfarth wrote
>     I have just started python, and want to know how to `exit'.  I was 
> hoping for the equivilent
> of the shell's `exit' or C's `exit()' function.  Note: when I tried 
> `exit', it didn't work...

>From the interpreter, you can use either Ctrl-D (UNIX) or Ctrl-Z (Win).
>From a program, you can use the exit function in the sys module; but
preferable, you should raise the SystemExit exception.  This is more in
keeping with catching or falling through toward the end of the program.

For example,

def do_something():
  ...
  if done:
    raise SystemExit(0)
  ...

try:
  ...
  do_something()
  ...
except SystemExit:
  pass # continue (in this example)... but in reduced capacity?
try:
  do_something()
finally:
  close_all_files()
# at this point, we'll terminate with a zero exit status

The sys.exit() function raises the SystemExit function, so there is
no difference.  Both of these also work in the interpreter as well.

  -Arcege

-- 
+----------------------------------+-----------------------------------+
| Michael P. Reilly                | arcege@speakeasy.net              |