作为序言,我要说的是,在大多数情况下,您不需要 Python 2 的内容exceptions
模块,因为它们可以在__builtin__
所有模块中的全局命名空间。但是,我们希望将其用于在线文档。
在这种情况下,简单的答案是 Python 2 的内容exceptions
为了保持一致性,模块已移至builtins
模块。
在 Python 3 shell 中:
>>> import builtins
>>> help(builtins)
将提供相同的文档。
如果您的路径上有 Python 3 的目录(也就是说,您可以在命令行上键入 python,它会调出 Python 3 shell),然后使用
$ pydoc builtins
我们会得到同样的。
如果你想测试这个,但你的路径上没有Python 3的pydoc,你可以使用以下两个命令在你的Python3.x目录中测试它,我得到了相同的输出:
$ python3 pydoc.py builtins
$ ./pydoc.py builtins
您将看到 Python 3 的异常层次结构(如下所示)以及文档的其余部分:
BaseException
Exception
ArithmeticError
FloatingPointError
OverflowError
ZeroDivisionError
AssertionError
AttributeError
BufferError
EOFError
ImportError
LookupError
IndexError
KeyError
MemoryError
NameError
UnboundLocalError
OSError
BlockingIOError
ChildProcessError
ConnectionError
BrokenPipeError
ConnectionAbortedError
ConnectionRefusedError
ConnectionResetError
FileExistsError
FileNotFoundError
InterruptedError
IsADirectoryError
NotADirectoryError
PermissionError
ProcessLookupError
TimeoutError
ReferenceError
RuntimeError
NotImplementedError
StopIteration
SyntaxError
IndentationError
TabError
SystemError
TypeError
ValueError
UnicodeError
UnicodeDecodeError
UnicodeEncodeError
UnicodeTranslateError
Warning
BytesWarning
DeprecationWarning
FutureWarning
ImportWarning
PendingDeprecationWarning
ResourceWarning
RuntimeWarning
SyntaxWarning
UnicodeWarning
UserWarning
GeneratorExit
KeyboardInterrupt
SystemExit
一位评论者说:
如果能包含一个 python 2/3 兼容性解决方案就好了。我的用例是语法荧光笔的所有异常名称的列表。
为了兼容性我会做这样的事情:
try:
import exceptions
except ImportError:
import builtins as exceptions
exceptions_list = sorted(n for n, e in vars(exceptions).items()
if isinstance(e, type) and
issubclass(e, BaseException))
你可以期待builtins
拥有 Python 3 中的所有内置异常,就像exceptions
Python 2 中就是这样做的 - 它也将具有其余的内置函数。
exceptions_list 可以是所有内置异常的规范列表。