您可以使用sys.last_value
:
>>> no_such_var
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'no_such_var' is not defined
>>> import sys
>>> sys.last_value
NameError("name 'no_such_var' is not defined",)
>>> sys.last_value.args
("name 'no_such_var' is not defined",)
>>> no_such_var
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'no_such_var' is not defined
>>> import pdb, sys
>>> pdb.set_trace()
--Return--
> <stdin>(1)<module>()->None
(Pdb) sys.last_value
NameError("name 'no_such_var' is not defined",)
注意:此解决方案并不完美。当未处理异常并且解释器打印错误消息和堆栈回溯时设置该值。例如,如果使用 , 捕获异常try .. except ..
,sys.last_value
则未设置。