Mortezaipo Mortezaipo - 1 year ago 131
Python Question

How to get python exception traceback in function

I have a function which should handle all errors:

def err(e):
import traceback
message = traceback.print_exc()

if __name__ == "__main__":
1/0 # just sample
except Exception as e:

But it returns a short error like so:

integer division or modulo by zero

But I need more details (
) to check errors.

Answer Source

You're passing the exception to your function so why use traceback, you've got e there; just grab e.__traceback__ if you need the traceback:

import traceback

def err(e):   
    tb = e.__traceback__
    # print traceback

For an option that doesn't depend on dunders, you could use sys.exc_info and keep the traceback:

import traceback, sys

def err(e):
    *_, tb = sys.exc_info()    
    # print traceback
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download