sys.exc_info() 的目的是什么?
What is the purpose of sys.exc_info()?
我想了解两者的区别:
try:
raise Exception("wat")
except Exception:
extype, exc, tb = sys.exc_info()
traceback.print_exception(extype, exc, tb)
和:
try:
raise Exception("wat")
except Exception as exc:
extype = type(exc)
tb = exc.__traceback__
traceback.print_exception(extype, exc, tb)
是否存在 type(exc)
和 exc.__traceback__
与 sys.exc_info()
编辑的值 return 不同的情况?如果不是,我应该什么时候更喜欢一个?当我对此进行测试时 (Python 3.7),returned 对象在引用上是相同的。
查看 CPython 中 exc_info()
的实现,第一个 return 值(异常类型)似乎是通过调用 PyExceptionInstance_Class 获得的,它是与 type(exc)
完全相同。但是,我找不到回溯是如何设置的。
(FWIW 我知道 traceback.print_exc()
shorthand,这与这个问题无关)
__traceback__
属性仅在 Python 3.0 之后可用,因此如果您希望使代码与 Python 2 兼容,则应改用 sys.exc_info()
;否则,根据 PEP-3134,__traceback__
属性的引入确实意味着完全取代 sys.exc_info()
,并可能弃用它:
In today's Python implementation, exceptions are composed of three
parts: the type, the value, and the traceback. The sys
module, exposes
the current exception in three parallel variables, exc_type
,
exc_value
, and exc_traceback
, the sys.exc_info()
function returns a
tuple of these three parts, and the raise statement has a
three-argument form accepting these three parts. Manipulating
exceptions often requires passing these three things in parallel,
which can be tedious and error-prone. Additionally, the except
statement can only provide access to the value, not the traceback.
Adding the __traceback__
attribute to exception values makes all the
exception information accessible from a single place.
我想了解两者的区别:
try:
raise Exception("wat")
except Exception:
extype, exc, tb = sys.exc_info()
traceback.print_exception(extype, exc, tb)
和:
try:
raise Exception("wat")
except Exception as exc:
extype = type(exc)
tb = exc.__traceback__
traceback.print_exception(extype, exc, tb)
是否存在 type(exc)
和 exc.__traceback__
与 sys.exc_info()
编辑的值 return 不同的情况?如果不是,我应该什么时候更喜欢一个?当我对此进行测试时 (Python 3.7),returned 对象在引用上是相同的。
查看 CPython 中 exc_info()
的实现,第一个 return 值(异常类型)似乎是通过调用 PyExceptionInstance_Class 获得的,它是与 type(exc)
完全相同。但是,我找不到回溯是如何设置的。
(FWIW 我知道 traceback.print_exc()
shorthand,这与这个问题无关)
__traceback__
属性仅在 Python 3.0 之后可用,因此如果您希望使代码与 Python 2 兼容,则应改用 sys.exc_info()
;否则,根据 PEP-3134,__traceback__
属性的引入确实意味着完全取代 sys.exc_info()
,并可能弃用它:
In today's Python implementation, exceptions are composed of three parts: the type, the value, and the traceback. The
sys
module, exposes the current exception in three parallel variables,exc_type
,exc_value
, andexc_traceback
, thesys.exc_info()
function returns a tuple of these three parts, and the raise statement has a three-argument form accepting these three parts. Manipulating exceptions often requires passing these three things in parallel, which can be tedious and error-prone. Additionally, the except statement can only provide access to the value, not the traceback. Adding the__traceback__
attribute to exception values makes all the exception information accessible from a single place.