You should check out the traceback module. Here’s the first example of an implementation, that popped in the forum search: