Home > Enterprise >  Get line number of a python function call in exception
Get line number of a python function call in exception

Time:05-29

I have a function like this

def try_strip(s):
    try:
        return s.strip()
    except Exception as e:
        print(e)
        # (I've tried inspect, traceback, logging, sys)

and if I call it somewhere like this

try_strip('could be a string or not')

then the exception line number would be the one in which the try_strip is defined. Is there a way to get info about where was it called? Thank you in advance.

CodePudding user response:

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".

The function traceback.format_stack() will return the stack trace information you need as a list of strings while the function 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 .

  • Related