繁体   English   中英

在异常中获取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 模块提供了此功能。 根据其文档:

提供标准接口来提取、格式化和打印 Python 程序的堆栈跟踪。 它在打印堆栈跟踪时完全模仿 Python 解释器的行为。

函数traceback.format_stack()会将您需要的堆栈跟踪信息作为字符串列表返回,而函数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

暂无
暂无

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

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