Program Exits
As we’ve seen, unlike C, there is no “main” function in Python.
When we run a program, we simply execute all of the code in the
top-level file, from top to bottom (i.e., in the filename we listed in
the command line, clicked in a file explorer, and so on). Scripts
normally exit when Python falls off the end of the file, but we may
also call for program exit explicitly with the built-in sys.exit
function:
>>>sys.exit(N)
# else exits
on end of script, with status N
Interestingly, this call really just raises the built-in
SystemExit
exception. Because of
this, we can catch it as usual to intercept early exits and perform
cleanup activities; if uncaught, the interpreter exits as usual. For
instance:
C:\...\PP3E\System>python
>>>import sys
>>>try:
...sys.exit( )
# see also: os._exit, Tk().quit( ) ...except SystemExit:
...print 'ignoring exit'
... ignoring exit >>>
In fact, explicitly raising the built-in SystemExit
exception with a Python raise
statement is equivalent to calling
sys.exit
. More realistically, a
try
block would catch the exit
exception raised elsewhere in a program; the script in Example 5-12 exits from within a
processing function.
Example 5-12. PP3E\System\Exits\testexit_sys.py
def later( ): import sys print 'Bye sys world' sys.exit(42) print 'Never reached' if _ _name_ _ == '_ _main_ _': later( )
Running this program as a script causes it to exit before the
interpreter falls off the end of the file. But because sys.exit
raises a Python exception, importers ...
Get Programming Python, 3rd Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.