< BACKMake Note | BookmarkCONTINUE >
156135250194107072078175030179198180025031194137176049106218111004228144072049161134074105

Terminating Execution

Clean execution occurs when a program runs to completion, where all statements in the top-level of your module finish execution and your program exits. There may be cases where you may want to exit from Python sooner, such as a fatal error of some sort. Another case is when conditions are not sufficient to continue execution.

In Python, there are varying ways to respond to errors. One is via exceptions and exception handling. Another way is to construct a "cleaner" approach so that the main portions of code are cordoned off with if statements to execute only in non-error situations, thus letting error scenarios terminate "normally." However, you may also desire to exit to the calling program with an error code to indicate that such an event has occurred.

sys.exit() and SystemExit

The primary way to exit a program immediately and return to the calling program is the exit() function found in the sys module. The syntax for sys.exit() is:

						
sys.exit(status=0)

					

When sys.exit() is called, a SystemExit exception is raised. Unless monitored (in a try statement with an appropriate except clause), this exception is generally not caught nor handled, and the interpreter exits with the given status argument, which defaults to zero if not provided. SystemExit is the only exception which is not viewed as an error. It simply indicates the desire to exit Python.

One popular place to use sys.exit() is after an error is discovered in the way a command was invoked. In particular, if the arguments are incorrect, invalid, or if there are an incorrect number of them. The following Example 14.4 (args.py) is just a test script we created to require that a certain number of arguments be given to the program before it can execute properly:

Executing this script we get the following output:

						
% args.py
At least 2 arguments required (incl. cmd name).
usage:  args.py arg1 arg2 [arg3… ]

% args.py XXX
At least 2 arguments required (incl. cmd name).
usage:  args.py arg1 arg2 [arg3… ]

% args.py 123 abc
number of args entered: 3
args (incl. cmd name) were: ['args.py', '123', 'abc' ]

% args.py -x -2 foo bar
number of args entered: 5
args (incl. cmd name) were: ['args.py', '-x', '-2', 'foo', 'bar' ]

					
Example 14.4. Exiting Immediately (args.py)

Calling sys.exit() causes the Python interpreter to quit. Any integer argument to exit() will be the returned to the caller as the exit status, which has a default value of 0.

							 <$nopage>
001 1  #!/usr/bin/env python
002 2
003 3  import sys
004 4
005 5  def usage():
006 6      print 'At least 2 arguments (incl. cmd name).'
007 7      print usage: args.py arg1 arg2 [arg3… ]'
008 8      sys.exit(1)
009 9
010 10 argc = len(sys.argv)
011 11 if argc < 3:
012 12     usage()
013 13 print "number of args entered:", argc
014 14 print "args (incl. cmd name) were:", sys.argv
015  <$nopage>
						

Many command-line driven programs test the validity of the input before proceeding with the core functionality of the script. If the validation fails at any point, a call is made to a usage() function to inform the user what problem caused the error as well as a usage "hint" to aid the user so that he or she will invoke the script properly the next time.

sys.exitfunc()

sys.exitfunc() is disabled by default, but can be overridden to provide additional functionality which takes place when sys.exit() is called and before the interpreter exits. This function will not be passed any arguments, so you should create your function to take no arguments.

As described in Beazley, if sys.exitfunc has already been overridden by a previously defined exit function, it is good practice to also execute that code as part of your exit function. Generally, exit functions are used to perform some type of shutdown activity, such as closing a file or network connection, and it is always a good idea to complete these maintenance tasks, such as releasing previously held system resources.

Here is an example of how to set up an exit function, being sure to execute one if one has already been set:

						 <$nopage>
001  <$nopage>import sys
002  <$nopage>
003 prev_exit_func = getattr(sys, 'exitfunc', None)
004  <$nopage>
005  <$nopage>def my_exit_func(old_exit = prev_exit_func):
006   #       :
007   # perform cleanup
008   #       :
009   if old_exit != None and callable(old_exit):
010      old_exit()
011  <$nopage>
012 sys.exitfunc = my_exit_func
013  <$nopage>
					

We execute the old exit function after our cleanup has been performed. The getattr() call simply checks to see whether a previous exitfunc has been defined. If not, then None is assigned to prev_exit_func; otherwise, prev_exit_func becomes a new alias to the exiting function, which is then passed as a default argument to our new exit function, my_exit_func.

The call to getattr() could have been rewritten as:

						 <$nopage>
001  <$nopage>if hasattr(sys, 'exitfunc'):
002     prev_exit_func = sys.exitfunc       # getattr(sys, 'exitfunc')
003  <$nopage>else: <$nopage>
004     prev_exit_func = None
005  <$nopage>
					

os._exit() Function

The _exit() function of the os module should not be used in general practice. (It is platform-dependent and available only on certain platforms anyway [Unix and Windows, to name a pair].) Its syntax is:

						 <$nopage>
001 os._exit(status)
002  <$nopage>
					

This function provides functionality opposite to that of sys.exit() and sys.exitfunc(), exiting Python immediately without performing any cleanup (Python or programmer-defined) at all. Unlike sys.exit(), the status argument is required. Exiting via sys.exit() is the preferred method of quitting the interpreter.


Last updated on 9/14/2001
Core Python Programming, © 2002 Prentice Hall PTR

< BACKMake Note | BookmarkCONTINUE >

© 2002, O'Reilly & Associates, Inc.