[Python编程(第4版)].(Programming.Python.4th.Edition).Mark.Lutz.文字版

(yzsuai) #1

normally exit when Python falls off the end of the file, but we may also call for program
exit explicitly with tools in the sys and os modules.


sys Module Exits


For example, the built-in sys.exit function ends a program when called, and earlier
than normal:


>>> sys.exit(N) # exit with status N, else exits on end of script

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:\...\PP4E\System> python
>>> import sys
>>> try:
... sys.exit() # see also: os._exit, Tk().quit()
... except SystemExit:
... print('ignoring exit')
...
ignoring exit
>>>

Programming tools such as debuggers can make use of this hook to avoid shutting
down. 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-15, for in-
stance, exits from within a processing function.


Example 5-15. PP4E\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
can trap and override its exit exception or specify a finally cleanup block to be run
during program exit processing:


C:\...\PP4E\System\Exits> python testexit_sys.py
Bye sys world

C:\...\PP4E\System\Exits> python
>>> from testexit_sys import later
>>> try:
... later()
... except SystemExit:

214 | Chapter 5: Parallel System Tools

Free download pdf