2

I need to make a Error log.txt in which when an error occurs, the whole content of that error should be written.

when doing except Exception as e: print(e) I only get the last line of the error. that is can only concatenate str (not "int") to str

I need the content to be

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

Desired text as above.

excelpanda
  • 73
  • 7

2 Answers2

0

You can use the traceback module's print_exc method to print complete traceback.

import traceback

error_file = open('errors.txt', 'w')
try:
    do_stuff()
except Exception, err:
    print Exception, err
traceback.print_exc(file=error_file)
  • How can I get this to a text file or a variable. Please read question – excelpanda Jun 07 '20 at 09:55
  • If you would have looked into the documentation of `print_exc` method then you would find the file parameter. With that parameter, you can pass a file object in which you want to write the same. – Mahendra Singh Meena Jun 08 '20 at 10:04
0

I got what I was looking for

try:

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

excelpanda
  • 73
  • 7