Get exception description and stack trace which caused an exception, all as a string

前端 未结 11 1955
旧巷少年郎
旧巷少年郎 2020-11-30 16:22

I\'ve seen a lot of posts about stack trace and exceptions in Python. But haven\'t found what I need.

I have a chunk of Python 2.7 code that may raise an exception.

11条回答
  •  旧巷少年郎
    2020-11-30 16:40

    For Python 3.5+:

    So, you can get the stacktrace from your exception as from any other exception. Use traceback.TracebackException for it (just replace ex with your exception):

    print("".join(traceback.TracebackException.from_exception(ex).format())
    

    An extended example and other features to do this:

    import traceback
    
    try:
        1/0
    except Exception as ex:
        print("".join(traceback.TracebackException.from_exception(ex).format()) == traceback.format_exc() == "".join(traceback.format_exception(type(ex), ex, ex.__traceback__))) # This is True !!
        print("".join(traceback.TracebackException.from_exception(ex).format()))
    

    The output will be something like this:

    True
    Traceback (most recent call last):
      File "untidsfsdfsdftled.py", line 29, in 
        1/0
    ZeroDivisionError: division by zero
    

提交回复
热议问题