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

(yzsuai) #1
... print('Ignored...')

Bye sys world
Ignored...
>>> try:
... later()
... finally:
... print('Cleanup')

Bye sys world
Cleanup

C:\...\PP4E\System\Exits> # interactive session process exits

os Module Exits


It’s possible to exit Python in other ways, too. For instance, within a forked child proc-
ess on Unix, we typically call the os._exit function rather than sys.exit; threads may
exit with a _thread.exit call; and tkinter GUI applications often end by calling some-
thing named Tk().quit(). We’ll meet the tkinter module later in this book; let’s take
a look at os exits here.


On os._exit, the calling process exits immediately instead of raising an exception that
could be trapped and ignored. In fact, the process also exits without flushing output
stream buffers or running cleanup handlers (defined by the atexit standard library
module), so this generally should be used only by child processes after a fork, where
overall program shutdown actions aren’t desired. Example 5-16 illustrates the basics.


Example 5-16. PP4E\System\Exits\testexit_os.py


def outahere():
import os
print('Bye os world')
os._exit(99)
print('Never reached')


if name == 'main': outahere()


Unlike sys.exit, os._exit is immune to both try/except and try/finally interception:


C:\...\PP4E\System\Exits> python testexit_os.py
Bye os world

C:\...\PP4E\System\Exits> python
>>> from testexit_os import outahere
>>> try:
... outahere()
... except:
... print('Ignored')
...
Bye os world # exits interactive process

C:\...\PP4E\System\Exits> python

Program Exits | 215
Free download pdf