自定义 python 回溯或调试输出



我有一个回溯打印,想要自定义它的最后一部分。

  • 内容:错误发生在另一个进程中,回溯在那里(就像在多处理中一样)。
  • 问题:我想获得完整的回溯和错误报告。

类似于以下代码:

>>> def f():
    g()
>>> def g():
    raise Exception, Exception(), None ## my traceback here
>>> f()
Traceback (most recent call last):
  File "<pyshell#14>", line 1, in <module>
    f()
  File "<pyshell#8>", line 2, in f
    g()
  File "<pyshell#11>", line 2, in g
    raise Exception, Exception(), None ## my traceback starts here
my traceback appears here
my traceback appears here
Exception

不可能的"解决方案":子类和模拟对象

>>> from types import *
>>> class CostomTB(TracebackType):
    pass

Traceback (most recent call last):
  File "<pyshell#125>", line 1, in <module>
    class CostomTB(TracebackType):
TypeError: Error when calling the metaclass bases
    type 'traceback' is not an acceptable base type
>>> class CostomTB(object):
    pass
>>> try: zzzzzzzzz
except NameError:
    import sys
    ty, err, tb = sys.exc_info()
    raise ty, err, CostomTB()

Traceback (most recent call last):
  File "<pyshell#133>", line 5, in <module>
    raise ty, err, CostomTB()
TypeError: raise: arg 3 must be a traceback or None

我正在使用python 2.7。

我想你想要完整的回溯堆栈。看到这个有非常好的例子 python 日志记录模块。
如果出现一些混淆,请参阅日志记录文档。

您提到了一个单独的过程:如果您的问题是捕获进程 A 中的回溯并将其显示在进程 B 中,就好像在后者中实际引发了异常一样,那么恐怕没有干净的方法来做到这一点。

我建议在进程 A 中序列化回溯,将其发送到进程 B,然后从那里引发一个新的异常,在其描述中包含前者。结果是输出稍长,但它携带有关两个进程堆栈的信息。

在下面的示例中,实际上没有两个单独的过程,但我希望它能更清楚地说明我的观点:

import traceback, StringI
def functionInProcessA():
    raise Exception('Something happened in A')
class RemoteException(Exception):
    def __init__(self, tb):
        Exception.__init__(self, "Remote traceback:nn%s" % tb)
def controlProcessB():
    try:
        functionInProcessA()
    except:
        fd = StringIO.StringIO()
        traceback.print_exc(file=fd)
        tb = fd.getvalue()
        raise RemoteException(tb)
if __name__ == '__main__':
    controlProcessB()

输出:

Traceback (most recent call last):
  File "a.py", line 20, in <module>
    controlProcessB()
  File "a.py", line 17, in controlProcessB
    raise RemoteException(tb)
__main__.RemoteException: Remote traceback:
Traceback (most recent call last):
  File "a.py", line 12, in controlProcessB
    functionInProcessA()
  File "a.py", line 4, in functionInProcessA
    raise Exception('Something happened in A')
Exception: Something happened in A

最新更新