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

Get line number of a python function call in exception

我有这样的功能

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

如果我这样称呼它

try_strip('could be a string or not')

那么异常行号就是定义了 try_strip 的行号。 有没有办法获取有关它在哪里调用的信息?提前谢谢你。

Python 中包含的 Traceback 模块提供了此功能。根据其文档:

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.

函数traceback.format_stack()将return您需要的堆栈跟踪信息作为字符串列表,而函数traceback.print_stack()将堆栈跟踪信息打印到控制台。下面我包含了一些代码,展示了如何在您提供的示例中使用它:

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

有关 Traceback 模块的更多信息,请参阅 https://docs.python.org/3/library/traceback.html