The Traceback module which is included with Python provides this functionality. According to its documentation it "provides a standard interface to extract, format and print stack traces of Python programs. It exactly mimics the behavior of the Python interpreter when it prints a stack trace".:
provides a standard interface to extract, format and print stack traces of Python programs. It exactly mimics the behaviour of the Python interpreter when it prints a stack trace.
The function traceback.format_stack()traceback.format_stack() will return the stack trace information you need as a list of strings while the function traceback.print_stack()traceback.print_stack() will print the stack trace information to the console. Below I have included some code which shows how you might use this in the example you provided:
import traceback def try_strip(s): try: return s.strip() except Exception as e: traceback.print_stack() stack_trace_info = traceback.format_stack() # Code that write stack_trace_info to a log could go here try_strip(5) # This will cause an error at runtime For additional info on the Traceback module, please see https://docs.python.org/3/library/traceback.html .