整个例外文本到文本文件

时间:2020-06-07 09:37:15

标签: python exception

我需要制作一个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

所需的文本。

2 个答案:

答案 0 :(得分:0)

您可以使用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)

答案 1 :(得分:0)

我找到了想要的东西

try:

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

相关问题