zoukankan      html  css  js  c++  java
  • python笔记71 traceback.print_exc()保存异常内容 上海

    前言

    python运行代码出现异常后,会在控制台输出报错内容,那么如何把报错的完整内容保存到日志文件中呢?

    try...expect捕获异常

    当运行下面的代码

    a = ["hello", "yoyo"]
    print(a[4])
    

    在控制台会输出异常

    Traceback (most recent call last):
      File "D:/demo/aa.py", line 4, in <module>
        print(a[4])
    IndexError: list index out of range
    

    可以通过try...expect捕获异常

    a = ["hello", "yoyo"]
    try:
        print(a[4])
    except Exception as e:
        print("异常类:{}".format(e.__class__.__name__))
        print("异常描述: {}".format(e))
    

    运行后输出

    异常类:IndexError
    异常描述: list index out of range
    

    这样虽然能捕获到异常的类和具体描述,但是没前面的详细,我们希望能捕获完整的Traceback内容

    traceback模块

    traceback模块被用来跟踪异常返回信息

    import traceback
    
    a = ["hello", "yoyo"]
    try:
        print(a[4])
    except Exception as e:
        traceback.print_exc()
    

    日志保存到文本

    import traceback
    
    a = ["hello", "yoyo"]
    try:
        print(a[4])
    except Exception as e:
        fp = open('log.txt', 'a')
        traceback.print_exc(file=fp)
        fp.close()
    

    于是在控制台就看不到异常的输出了,异常的内容会输出到log.txt文件

    StringIO 写入内存

    如果不想写入到文件,也可以暂时写入到内存(StringIO),后面需要用到的时候再读出来

    from io import StringIO
    import traceback
    
    a = ["hello", "yoyo"]
    
    fp = StringIO()
    try:
        print(a[4])
    except Exception as e:
        traceback.print_exc(file=fp)
    
    print("----后续代码用到地方读出来----")
    print(fp.getvalue())
    

    运行结果

    ----后续代码用到地方读出来----
    Traceback (most recent call last):
      File "D:/demo/myweb/aa.py", line 8, in <module>
        print(a[4])
    IndexError: list index out of range
    
  • 相关阅读:
    1.27
    1.25
    Representation Learning with Contrastive Predictive Coding
    Learning a Similarity Metric Discriminatively, with Application to Face Verification
    噪声对比估计(负样本采样)
    Certified Adversarial Robustness via Randomized Smoothing
    Certified Robustness to Adversarial Examples with Differential Privacy
    Dynamic Routing Between Capsules
    Defending Adversarial Attacks by Correcting logits
    Visualizing Data using t-SNE
  • 原文地址:https://www.cnblogs.com/yoyoketang/p/15592804.html
Copyright © 2011-2022 走看看