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