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

(yzsuai) #1

We might use such a hook to write programs that display or otherwise process all the
modules loaded by a program (just iterate over the keys of sys.modules).


Also in the interpret hooks category, an object’s reference count is available via
sys.getrefcount, and the names of modules built-in to the Python executable are listed
in sys.builtin_module_names. See Python’s library manual for details; these are mostly
Python internals information, but such hooks can sometimes become important to
programmers writing tools for other programmers to use.


Exception Details


Other attributes in the sys module allow us to fetch all the information related to the
most recently raised Python exception. This is handy if we want to process exceptions
in a more generic fashion. For instance, the sys.exc_info function returns a tuple with
the latest exception’s type, value, and traceback object. In the all class-based exception
model that Python 3 uses, the first two of these correspond to the most recently raised
exception’s class, and the instance of it which was raised:


>>> try:
... raise IndexError
... except:
... print(sys.exc_info())
...
(<class 'IndexError'>, IndexError(), <traceback object at 0x019B8288>)

We might use such information to format our own error message to display in a GUI
pop-up window or HTML web page (recall that by default, uncaught exceptions ter-
minate programs with a Python error display). The first two items returned by this call
have reasonable string displays when printed directly, and the third is a traceback object
that can be processed with the standard traceback module:


>>> import traceback, sys
>>> def grail(x):
... raise TypeError('already got one')
...
>>> try:
... grail('arthur')
... except:
... exc_info = sys.exc_info()
... print(exc_info[0])
... print(exc_info[1])
... traceback.print_tb(exc_info[2])
...
<class 'TypeError'>
already got one
File "<stdin>", line 2, in <module>
File "<stdin>", line 2, in grail

The traceback module can also format messages as strings and route them to specific
file objects; see the Python library manual for more details.


Introducing the sys Module | 89
Free download pdf