有时在我调试时会引发异常。
例如,考虑以下代码:
def some_function(): # Pretend this function is in a library...
# ...and deep within the library is an exception:
raise Exception('An exception message with valuable information.')
import pdb; pdb.set_trace()
try:
some_function() # Pretend I am debugging from this point using pdb.
except:
pass
在从 some_function()
调用进行调试时,如果我发出 next
命令,我将看到以下有关引发[并捕获]的异常的详细信息:
Exception: Exceptio...ation.',)
这是从我工作的终端直接复制/粘贴的:
> /tmp/test.py(7)<module>()
-> some_function() # Pretend I am debugging from this point using pdb.
(Pdb) next
Exception: Exceptio...ation.',)
> /tmp/test.py(7)<module>()
-> some_function() # Pretend I am debugging from this point using pdb.
(Pdb)
查看整个异常消息会很有用。如何在 pdb 中执行此操作?
最佳答案
pdb
将异常类型和值存储在 __exception__
中。您可以使用以下命令在 pdb
中打印回溯的异常部分:
import traceback; print "".join(traceback.format_exception_only(*__exception__))
例如:
> /tmp/test.py(7)<module>()
-> some_function() # Pretend I am debugging from this point using pdb.
(Pdb) next
Exception: Exceptio...ation.',)
> /tmp/test.py(7)<module>()
-> some_function() # Pretend I am debugging from this point using pdb.
(Pdb) import traceback; print "".join(traceback.format_exception_only(*__exception__))
Exception: An exception message with valuable information.
(Pdb)
不幸的是,这不包括其余的回溯,但是所有这些信息都可以通过 pdb
的 where
命令获得。如果您真的想要完整的回溯,您可以将以下内容添加到您的 ~/.pdbrc
文件中或将其粘贴到您的终端中:
!global __currentframe, __stack; from inspect import currentframe as __currentframe, stack as __stack
!global __format_exception_only, __print_stack; from traceback import format_exception_only as __format_exception_only, print_stack as __print_stack
!global __Pdb; from pdb import Pdb as __Pdb
# find the last frame on the stack with an object named "pdb" or "self" that is a pdb.Pdb object
# works for pdb called the usual way, or pdb.pm(), or pdb.set_trace()
!global __pdb; __pdb = [__framerec[0].f_locals.get("pdb") or __framerec[0].f_locals.get("self") for __framerec in __stack() if (__framerec[0].f_locals.get("pdb") or __framerec[0].f_locals.get("self")).__class__ == __Pdb][-1]
alias traceback __print_stack(__pdb.stack[-1][0]); print "".join(__format_exception_only(*__exception__))
然后你可以使用新的 traceback
别名来得到你想要的:
> /tmp/test.py(7)<module>()
-> some_function() # Pretend I am debugging from this point using pdb.
(Pdb) next
Exception: Exceptio...ation.',)
> /tmp/test.py(7)<module>()
-> some_function() # Pretend I am debugging from this point using pdb.
(Pdb) traceback
File "test.py", line 7, in <module>
some_function() # Pretend I am debugging from this point using pdb.
File "test.py", line 3, in some_function
raise Exception('An exception message with valuable information.')
Exception: An exception message with valuable information.
(Pdb)
警告:所有这些都依赖于未记录的 pdb
和 bdb
内部结构,并且可能会中断。
关于python - 如何在 Python 的调试器中查看异常的详细信息?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6241200/