Program Exits
As we’ve seen, unlike C there is no “main” function
in Python -- when we run a program, we simply execute all 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( ) # else exits on end of scriptInterestingly, 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:\...\PP2E\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 3-11
exits from within a processing function.
Example 3-11. PP2E\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 of its function ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access