I want to save the name of the error and the traceback details into a variable. Here\'s is my attempt.
import sys
try:
try:
print x
except E
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()
[
('', 1, '', 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)'),
('', 1, '', None)
]
Here's the output from ''.join(traceback.format_stack()). Formatting added for readability.
>>> ''.join(traceback.format_stack())
' File "", line 1, in \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 "", line 1, in \n'