简体   繁体   English

在异常中获取python函数调用的行号

[英]Get line number of a python function call in exception

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.那么异常行号将是定义 try_strip 的行号。 Is there a way to get info about where was it called?有没有办法获取有关它在哪里调用的信息? Thank you in advance.先感谢您。

The Traceback module which is included with Python provides this functionality. Python 中包含的 Traceback 模块提供了此功能。 According to its documentation it:根据其文档:

provides a standard interface to extract, format and print stack traces of Python programs.提供标准接口来提取、格式化和打印 Python 程序的堆栈跟踪。 It exactly mimics the behaviour of the Python interpreter when it prints a stack trace.它在打印堆栈跟踪时完全模仿 Python 解释器的行为。

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.函数traceback.format_stack()会将您需要的堆栈跟踪信息作为字符串列表返回,而函数traceback.print_stack()会将堆栈跟踪信息打印到控制台。 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 .有关 Traceback 模块的更多信息,请参阅https://docs.python.org/3/library/traceback.html

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM