【问题标题】:Formatting and capturing sys.exc_info error messages格式化和捕获 sys.exc_info 错误消息
【发布时间】:2021-07-26 21:39:49
【问题描述】:

我正在尝试通过''.join(traceback.format_stack()) 格式化和获取来自 sys.exc_info 的信息,但没有运气,关于如何将 sys.esc_info 中的所有信息转换为字符串的任何建议。我最终需要将所有这些信息写入一个表中。

【问题讨论】:

    标签: python logging error-handling


    【解决方案1】:

    使用sys.exc_info() 获取异常三元组。要从跟踪中获取字符串,请使用traceback.format_tb()

    #!/usr/bin/env python
    
    import sys
    import traceback
    
    try:
        raise RuntimeError("This is an error")
    except:
        exception_type, exception_value, trace = sys.exc_info()
        print(f"Exception type: {exception_type}") # <class 'RuntimeError'>
        print(f"Exception value: {exception_value}") # This is an error
    
        trace_string = "".join(traceback.format_tb(trace))
        print(f"Stack trace:\n{trace_string}")
        # File "/home/pierre/stackoverflow.py", line 5, in <module>
        #     raise RuntimeError("This is an error")
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-07-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多