2
import traceback  
try:  
   1/0  
except Exception,e:  
   traceback.print_exc()  

The output is as follow:

Traceback (most recent call last):
File "test_traceback.py", line 3, in <module>
1/0
ZeroDivisionError: integer division or modulo by zero

However I don't want to use traceback.print_exc() to print the output. Instead, I want to save the output to a variable. How can I do that?

Ronan Boiteau
  • 9,608
  • 6
  • 34
  • 56
Jay
  • 113
  • 8
  • 1
    Related: [How to save traceback / sys.exc_info() values in a variable?](https://stackoverflow.com/questions/8238360/how-to-save-traceback-sys-exc-info-values-in-a-variable) – Ilja Everilä Dec 29 '17 at 08:48

2 Answers2

4

Use traceback.format_exc():

import traceback

try:
   1/0
except Exception:
   trace = traceback.format_exc()
   print trace

From the Python documentation:

traceback.format_exc([limit])

This is like print_exc(limit) but returns a string instead of printing to a file.

Community
  • 1
  • 1
Ronan Boiteau
  • 9,608
  • 6
  • 34
  • 56
0

Try this:

import traceback  
try:  
   1/0  
except Exception as e:  
   error = traceback.format_exc()


print(error)
johnII
  • 1,423
  • 1
  • 14
  • 20