【问题标题】:Whole Exception text to a text file整个异常文本到文本文件
【发布时间】:2020-06-07 09:37:15
【问题描述】:

我需要创建一个Error log.txt,在其中发生错误时,应写入该错误的全部内容。

在执行except Exception as e: print(e) 时,我只得到错误的最后一行。那是can only concatenate str (not "int") to str

我需要的内容是

Traceback (most recent call last):
  File "E:\lib\site-packages\pandas\core\ops\array_ops.py", line 149, in na_arithmetic_op
    result = expressions.evaluate(op, str_rep, left, right)
  File "E:\lib\site-packages\pandas\core\computation\expressions.py", line 208, in evaluate
    return _evaluate(op, op_str, a, b)
  File "E:\lib\site-packages\pandas\core\computation\expressions.py", line 70, in _evaluate_standard
    return op(a, b)
TypeError: can only concatenate str (not "int") to str

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "E:/checking sum.py", line 9, in <module>
    df2.index = df2.index + 2
  File "E:\lib\site-packages\pandas\core\indexes\base.py", line 2119, in __add__
    return Index(Series(self) + other)
  File "E:\lib\site-packages\pandas\core\ops\common.py", line 64, in new_method
    return method(self, other)
  File "E:\lib\site-packages\pandas\core\ops\__init__.py", line 503, in wrapper
    result = arithmetic_op(lvalues, rvalues, op, str_rep)
  File "E:\lib\site-packages\pandas\core\ops\array_ops.py", line 197, in arithmetic_op
    res_values = na_arithmetic_op(lvalues, rvalues, op, str_rep)
  File "E:\lib\site-packages\pandas\core\ops\array_ops.py", line 151, in na_arithmetic_op
    result = masked_arith_op(left, right, op)
  File "E:\lib\site-packages\pandas\core\ops\array_ops.py", line 112, in masked_arith_op
    result[mask] = op(xrav[mask], y)
TypeError: can only concatenate str (not "int") to str

所需文字如上。

【问题讨论】:

标签: python exception


【解决方案1】:

我得到了我想要的东西

try:

except:
    error = traceback.format_exc()
    with open('mytxt.txt') as text:
           text.write(error)

【讨论】:

    【解决方案2】:

    您可以使用traceback 模块的print_exc 方法打印完整的回溯。

    import traceback
    
    error_file = open('errors.txt', 'w')
    try:
        do_stuff()
    except Exception, err:
        print Exception, err
    traceback.print_exc(file=error_file)
    

    【讨论】:

    • 我怎样才能把它放到文本文件或变量中。请阅读问题
    • 如果您查看了print_exc 方法的文档,那么您会找到文件参数。使用该参数,您可以传递要在其中写入相同内容的文件对象。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-09
    • 1970-01-01
    • 2021-12-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多