pdb
存储异常类型和价值倾倒在你的代码中的任何点的堆栈跟踪。
import traceback; print "".join(traceback.format_exception_only(*__exception__))
例如:你可以用打印回溯外部分pdb
> /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)
不幸的是,这并不包括回溯的休息,但所有这些信息是可以通过where
无论如何,pdb
的命令。如果你真的想完整回溯,你可以添加以下到您的~/.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?我的矿井不会像那样截断。 – Keith 2011-06-05 08:46:53
版本2.7.1。请注意,raise语句是完整打印的,所以乍一看你可能会打印整个异常,但是当实际的异常被pdb截取(我不知道这个术语)时,它会被截断。 – Buttons840 2011-06-05 17:43:05
嗯,我实际上编写了我自己的Python调试器的变体,它不会这样做,也意味着自动进入调试器(使用sys.excepthook)。如果你喜欢,你可以尝试一下。它是[调试器](http://code.google.com/p/pycopia/source/browse/#svn%2Ftrunk%2Fdebugger)子包。 – Keith 2011-06-06 01:44:55