Extract traceback info from an exception object

后端 未结 5 1566
忘掉有多难
忘掉有多难 2020-12-02 10:31

Given an Exception object (of unknown origin) is there way to obtain its traceback? I have code like this:

def stuff():
   try:
       .....
       return us         


        
5条回答
  •  鱼传尺愫
    2020-12-02 10:46

    There's a very good reason the traceback is not stored in the exception; because the traceback holds references to its stack's locals, this would result in a circular reference and (temporary) memory leak until the circular GC kicks in. (This is why you should never store the traceback in a local variable.)

    About the only thing I can think of would be for you to monkeypatch stuff's globals so that when it thinks it's catching Exception it's actually catching a specialised type and the exception propagates to you as the caller:

    module_containing_stuff.Exception = type("BogusException", (Exception,), {})
    try:
        stuff()
    except Exception:
        import sys
        print sys.exc_info()
    

提交回复
热议问题