[Tutor] import sys; sys.exit()

Steve Willoughby steve at alchemy.com
Thu Jan 10 22:32:11 CET 2008


On Thu, Jan 10, 2008 at 01:17:20PM -0800, Andrew Volmensky wrote:
> When typing the commands [statements?] in the terminal I get this:
> 
> Last login: Sat Jan  5 22:20:44 on ttyp2
> Welcome to Darwin!
> warewerks-01:~ andrew$ python
> Python 2.4.4 (#1, Oct 18 2006, 10:34:39)
> [GCC 4.0.1 (Apple Computer, Inc. build 5341)] on darwin
> Type "help", "copyright", "credits" or "license" for more information.
>  >>> import sys
>  >>> sys.exit()
> warewerks-01:~ andrew$
> 
> Does that behavior look correct? Apparently I have exit out of the  
> Python interpreter; yes?

Yes.

In a running program, a SystemExit exception will, unless some part 
of your program is specfically watching to intercept it, terminate
your program.  In your example above, you are exiting the interpreter.

If you were in IDLE instead of a terminal window, the GUI would 
catch it and ask you if you wanted to exit IDLE or just go back
to an interactive Python interpreter prompt.

> Kent - also thank you! I hope "exceptions" are covered in a following  
> tutorial!

Exceptions are something you should have at least basic familiarity
with (as a general concept, not necessarily a lot of detail) fairly 
soon upon starting to learn Python.  At least this much:

An exception is an error event raised by some part of your program
which ran into trouble trying to carry out an operation.  Normally,
the exception is printed out with some amount of relevant information
like "Division by zero error!" or "Permission denied opening foo.txt"
and your program will exit.

An uncaught exception raised in a function will immediately terminate
that function, and if the calling function wasn't set up to catch that
exception, then it's terminated too, and so on up the levels of the
call stack until something deals with that issue or you run out of 
levels to exit and you fall out of your program completely.

If you want to have Python try to run a block of code but let you
handle any exceptions which occur, you can do this:

  try:
    (insert your code here...)
  except:
    (the code here is run if anything in
    the "try" block failed...)

If you want to handle a specific exception only, you can do
something like in this example:

  try:
    spam = int(message_qty)
  except ValueError:
    spam = 0
    print "Warning:", message_qty, "is not a valid-looking number"
    print "proceeding with a value of 0 instead."

If the int() function raises a ValueError, the code here will 
deal gracefully with that, and carry on.  Any other exception
will still be handled normally.

There's a lot more detail, but that's the basic gist of it.

-- 
Steve Willoughby    |  Using billion-dollar satellites
steve at alchemy.com   |  to hunt for Tupperware.


More information about the Tutor mailing list