Python 中的堆栈跟踪显示文件路径。有没有办法让他们显示完全限定的函数名?
例子:
class Foo(object):
def bar(self):
raise Exception, "Some error."
def inner():
return Foo().bar()
def outer():
return inner()
我希望我的输出看起来像这样:
In __main__.Foo.bar ("scratchpad.py", line 3)
__main__.inner ("scratchpad.py", line 6)
__main__.outer ("scratchpad.py", line 9)
Exception: Some error.
如果它有任何改变,我使用的是 Python 2.7。
这是我到目前为止所拥有的:
import sys
class Foo(object):
def bar(self):
raise Exception, "Dummy value."
def inner():
"Inner function..."
return Foo().bar()
def outer():
return inner()
try:
outer()
except Exception, error:
traceback = sys.exc_info()[2]
while traceback is not None:
frame = traceback.tb_frame
print 'Name', frame.f_globals['__name__']+'.'+frame.f_code.co_name
docs = frame.f_code.co_consts[0]
if docs and docs != -1: # docs can be None or -1.
print 'Docs "%s"' % docs
print 'Args', frame.f_code.co_argcount
print 'File "%s", line %d' % (frame.f_code.co_filename, frame.f_lineno)
print
traceback = traceback.tb_next
当我运行它时,它会打印
$ python pretty-stack.py
Name __main__.<module>
Args 0
File "pretty-stack.py", line 28
Name __main__.outer
Args 0
File "pretty-stack.py", line 14
Name __main__.inner
Docs "Inner function..."
Args 0
File "pretty-stack.py", line 11
Name __main__.bar
Args 1
File "pretty-stack.py", line 7
它几乎就在那里,但我在重要的用例上遇到了麻烦。例如,我无法Foo
获取Foo.bar()
.