How to save traceback / sys.exc_info() values in a variable?
Use traceback.extract_stack()
if you want convenient access to module and function names and line numbers.
Use ''.join(traceback.format_stack())
if you just want a string that looks like the traceback.print_stack()
output.
Notice that even with ''.join()
you will get a multi-line string, since the elements of format_stack()
contain \n
. See output below.
Remember to import traceback
.
Here's the output from traceback.extract_stack()
. Formatting added for readability.
>>> traceback.extract_stack()
[
('<string>', 1, '<module>', None),
('C:\\Python\\lib\\idlelib\\run.py', 126, 'main', 'ret = method(*args, **kwargs)'),
('C:\\Python\\lib\\idlelib\\run.py', 353, 'runcode', 'exec(code, self.locals)'),
('<pyshell#1>', 1, '<module>', None)
]
Here's the output from ''.join(traceback.format_stack())
. Formatting added for readability.
>>> ''.join(traceback.format_stack())
' File "<string>", line 1, in <module>\n
File "C:\\Python\\lib\\idlelib\\run.py", line 126, in main\n
ret = method(*args, **kwargs)\n
File "C:\\Python\\lib\\idlelib\\run.py", line 353, in runcode\n
exec(code, self.locals)\n File "<pyshell#2>", line 1, in <module>\n'
This is how I do it:
>>> import traceback
>>> try:
... int('k')
... except:
... var = traceback.format_exc()
...
>>> print var
Traceback (most recent call last):
File "<stdin>", line 2, in <module>
ValueError: invalid literal for int() with base 10: 'k'
You should however take a look at the traceback documentation, as you might find there more suitable methods, depending to how you want to process your variable afterwards...
sys.exc_info() returns a tuple with three values (type, value, traceback).
- Here type gets the exception type of the Exception being handled
- value is the arguments that are being passed to constructor of exception class
- traceback contains the stack information like where the exception occurred etc.
For Example, In the following program
try:
a = 1/0
except Exception,e:
exc_tuple = sys.exc_info()
Now If we print the tuple the values will be this.
- exc_tuple[0] value will be "ZeroDivisionError"
- exc_tuple[1] value will be "integer division or modulo by zero" (String passed as parameter to the exception class)
- exc_tuple[2] value will be "trackback object at (some memory address)"
The above details can also be fetched by simply printing the exception in string format.
print str(e)