15.04.2013 Views

Core Python Programming (2nd Edition)

Core Python Programming (2nd Edition)

Core Python Programming (2nd Edition)

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Calling sys.exit() causes the <strong>Python</strong> interpreter to quit. Any integer argument to exit() will<br />

be returned to the caller as the exit status, which has a default value of 0.<br />

1 #!/usr/bin/env python<br />

2<br />

3 import sys<br />

4<br />

5 def usage():<br />

6 print 'At least 2 arguments (incl. cmd name).'<br />

7 print 'usage: args.py arg1 arg2 [arg3... ]'<br />

8 sys.exit(1)<br />

9<br />

10 argc = len(sys.argv)<br />

11 if argc < 3:<br />

12 usage()<br />

13 print "number of args entered:", argc<br />

14 print "args (incl. cmd name) were:", sys.argv<br />

Many command-line-driven programs test the validity of the input before proceeding with the core<br />

functionality of the script. If the validation fails at any point, a call is made to a usage() function to<br />

inform the user what problem caused the error as well as a usage "hint" to aid the user so that he or<br />

she will invoke the script properly the next time.<br />

14.7.2. sys.exitfunc()<br />

sys.exitfunc() is disabled by default, but can be overridden to provide additional functionality, which<br />

takes place when sys.exit() is called and before the interpreter exits. This function will not be passed<br />

any arguments, so you should create your function to take no arguments.<br />

If sys.exitfunc has already been overridden by a previously defined exit function, it is good practice to<br />

also execute that code as part of your exit function. Generally, exit functions are used to perform some<br />

type of shutdown activity, such as closing a file or network connection, and it is always a good idea to<br />

complete these maintenance tasks, such as releasing previously held system resources.<br />

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

set:<br />

import sys<br />

prev_exit_func = getattr(sys, 'exitfunc', None)<br />

def my_exit_func(old_exit = prev_exit_func):<br />

# :<br />

# perform cleanup<br />

# :<br />

if old_exit is not None and callable(old_exit):<br />

old_exit()<br />

sys.exitfunc = my_exit_func

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!