15.04.2013 Views

Core Python Programming (2nd Edition)

Core Python Programming (2nd Edition)

Core Python Programming (2nd Edition)

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

14.7. Terminating Execution<br />

Clean execution occurs when a program runs to completion, where all statements in the top level of<br />

your module finish execution and your program exits. There may be cases where you may want to exit<br />

from <strong>Python</strong> sooner, such as a fatal error of some sort. Another case is when conditions are not<br />

sufficient to continue execution.<br />

In <strong>Python</strong>, there are varying ways to respond to errors. One is via exceptions and exception handling.<br />

Another way is to construct a "cleaner" approach so that the main portions of code are cordoned off with<br />

if statements to execute only in non-error situations, thus letting error scenarios terminate "normally."<br />

However, you may also desire to exit the calling program with an error code to indicate that such an<br />

event has occurred.<br />

14.7.1. sys.exit() and SystemExit<br />

The primary way to exit a program immediately and return to the calling program is the exit() function<br />

found in the sys module. The syntax for sys.exit() is:<br />

sys.exit(status=0)<br />

When sys.exit() is called, a SystemExit exception is raised. Unless monitored (in a try statement with<br />

an appropriate except clause), this exception is generally not caught or handled, and the interpreter<br />

exits with the given status argument, which defaults to zero if not provided. System Exit is the only<br />

exception that is not viewed as an error. It simply indicates the desire to exit <strong>Python</strong>.<br />

One popular place to use sys.exit() is after an error is discovered in the way a command was invoked,<br />

in particular, if the arguments are incorrect, invalid, or if there are an incorrect number of them. The<br />

following Example 14.4 (args.py) is just a test script we created to require that a certain number of<br />

arguments be given to the program before it can execute properly.<br />

Executing this script we get the following output:<br />

$ args.py<br />

At least 2 arguments required (incl. cmd name).<br />

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

$ args.py XXX<br />

At least 2 arguments required (incl. cmd name).<br />

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

$ args.py 123 abc<br />

number of args entered: 3<br />

args (incl. cmd name) were: ['args.py', '123', 'abc']<br />

$ args.py -x -2 foo<br />

number of args entered: 4<br />

args (incl. cmd name) were: ['args.py', '-x', '-2',<br />

'foo']<br />

Example 14.4. Exiting Immediately (args.py)

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

Saved successfully!

Ooh no, something went wrong!