1

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

  • 什么:错误发生在另一个进程中,并且回溯在那里(就像多处理中的情况一样)。
  • 问题:我想要完整的回溯和错误报告。

类似于此代码:

>>> 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。

4

2 回答 2

1

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

于 2012-08-09T21:51:05.687 回答
0

您提到了一个单独的进程:如果您的问题是在进程 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:\n\n%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
于 2012-08-10T08:26:40.117 回答