Section 14.7. Terminating Execution


14.7. 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 the calling program with an error code to indicate that such an event has occurred.

14.7.1. 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 or handled, and the interpreter exits with the given status argument, which defaults to zero if not provided. System Exit is the only exception that 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     number of args entered: 4     args (incl. cmd name) were: ['args.py', '-x', '-2',     'foo']


Example 14.4. Exiting Immediately (args.py)

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

1  #!/usr/bin/env       python 2 3  import    sys 4 5  def usage(): 6      print 'At least 2 arguments (incl. cmd name).' 7      print 'usage: args.py arg1 arg2 [arg3... ]' 8      sys.exit(1) 9 10 argc = len(sys.argv) 11 if argc < 3: 12     usage() 13 print  "number of args entered:", argc 14 print  "args (incl. cmd name) were:", sys.argv

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.

14.7.2. 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.

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:

        import sys     prev_exit_func = getattr(sys, 'exitfunc', None)     def my_exit_func(old_exit = prev_exit_func):      #       :      # perform cleanup      #       :      if old_exit is not None and callable(old_exit):         old_exit()     sys.exitfunc = my_exit_func


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:

    if hasattr(sys, 'exitfunc'):         prev_exit_func  = sys.exitfunc  # getattr(sys, 'exitfunc') else:         prev_exit_func = None


14.7.3. 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, i.e., Unix-based and Win32.) Its syntax is:

    os._exit(status)


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.

14.7.4. os.kill() Function

The kill() function of the os module performs the traditional Unix function of sending a signal to a process. The arguments to kill() are the process identification number (PID) and the signal you wish to send to that process. The typical signal that is sent is either SIGINT, SIGQUIT, or more drastically, SIGKILL, to cause a process to terminate.



Core Python Programming
Core Python Programming (2nd Edition)
ISBN: 0132269937
EAN: 2147483647
Year: 2004
Pages: 334
Authors: Wesley J Chun

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net