traceback.format_exc() will yield more info if that's what you want.
import traceback
def do_stuff():
raise Exception("test exception")
try:
do_stuff()
except Exception:
print(traceback.format_exc())
This outputs:
Traceback (most recent call last):
File "main.py", line 9, in <module>
do_stuff()
File "main.py", line 5, in do_stuff
raise Exception("test exception")
Exception: test exception
Answer from volting on Stack OverflowPrint Full Python Traceback Without Halting Program - TestMu AI Community
Print traceback without an exception
debugging - print python stack trace without exception being raised - Stack Overflow
python - Print an error message without printing a traceback and close the program when a condition is not met - Stack Overflow
Videos
traceback.format_exc() will yield more info if that's what you want.
import traceback
def do_stuff():
raise Exception("test exception")
try:
do_stuff()
except Exception:
print(traceback.format_exc())
This outputs:
Traceback (most recent call last):
File "main.py", line 9, in <module>
do_stuff()
File "main.py", line 5, in do_stuff
raise Exception("test exception")
Exception: test exception
Some other answer have already pointed out the traceback module.
Please notice that with print_exc, in some corner cases, you will not obtain what you would expect. In Python 2.x:
import traceback
try:
raise TypeError("Oups!")
except Exception, err:
try:
raise TypeError("Again !?!")
except:
pass
traceback.print_exc()
...will display the traceback of the last exception:
Traceback (most recent call last):
File "e.py", line 7, in <module>
raise TypeError("Again !?!")
TypeError: Again !?!
If you really need to access the original traceback one solution is to cache the exception infos as returned from exc_info in a local variable and display it using print_exception:
import traceback
import sys
try:
raise TypeError("Oups!")
except Exception, err:
try:
exc_info = sys.exc_info()
# do you usefull stuff here
# (potentially raising an exception)
try:
raise TypeError("Again !?!")
except:
pass
# end of useful stuff
finally:
# Display the *original* exception
traceback.print_exception(*exc_info)
del exc_info
Producing:
Traceback (most recent call last):
File "t.py", line 6, in <module>
raise TypeError("Oups!")
TypeError: Oups!
Few pitfalls with this though:
From the doc of
sys_info:Assigning the traceback return value to a local variable in a function that is handling an exception will cause a circular reference. This will prevent anything referenced by a local variable in the same function or by the traceback from being garbage collected. [...] If you do need the traceback, make sure to delete it after use (best done with a try ... finally statement)
but, from the same doc:
Beginning with Python 2.2, such cycles are automatically reclaimed when garbage collection is enabled and they become unreachable, but it remains more efficient to avoid creating cycles.
On the other hand, by allowing you to access the traceback associated with an exception, Python 3 produce a less surprising result:
import traceback
try:
raise TypeError("Oups!")
except Exception as err:
try:
raise TypeError("Again !?!")
except:
pass
traceback.print_tb(err.__traceback__)
... will display:
File "e3.py", line 4, in <module>
raise TypeError("Oups!")
traceback.print_stack():
>>> def f():
... def g():
... traceback.print_stack()
... g()
...
>>> f()
File "<stdin>", line 1, in <module>
File "<stdin>", line 4, in f
File "<stdin>", line 3, in g
Edit: You can also use extract_stack, take a slice (e.g. stack[5:] for exclude the first 5 levels) and use format_list to get a print-ready stacktrace ('\n'.join(traceback.format_list(...)))
Instead of printing to stdout, if you need a string to pass to a logger you can use:
''.join(traceback.format_stack())
Note, that traceback.format_stack() returns the stacktrace as a formatted list of strings, so you can slice it anyway you want. To get the last few elements of the stacktrace you could do:
''.join(traceback.format_stack()[-N:])
Where N is the number of levels you are interested in.
You can turn off the traceback by limiting its depth.
Python 2.x
import sys
sys.tracebacklimit = 0
Python 3.x
In Python 3.5.2 and 3.6.1, setting tracebacklimit to 0 does not seem to have the intended effect. This is a known bug. Note that -1 doesn't work either. Setting it to None does however seem to work, at least for now.
In Python 3.6.2 and above you should set tracebacklimit to 0 or -1, as setting it to None does not disable the traceback output.
Python 3.6.1 and below results:
>>> import sys
>>> sys.tracebacklimit = 0
>>> raise Exception
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
Exception
>>> sys.tracebacklimit = -1
>>> raise Exception
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
Exception
>>> sys.tracebacklimit = None
>>> raise Exception
Exception
Python 3.6.2 and above results:
>>> import sys
>>> sys.tracebacklimit = 0
>>> raise Exception
Exception
>>> sys.tracebacklimit = -1
>>> raise Exception
Exception
>>> sys.tracebacklimit = None
>>> raise Exception
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
Exception
Nevertheless, for better or worse, if multiple exceptions are raised, they can all still be printed. For example:
socket.gaierror: [Errno -2] Name or service not known
During handling of the above exception, another exception occurred:
urllib.error.URLError: <urlopen error [Errno -2] Name or service not known>
You can use SystemExit exception:
except Exception as err:
raise SystemExit(err)
See the documentation on SystemExit for more details.
I've been dealing with legacy code that uses Try Excepts. The issue I'm having is that when a failure occurs the stack trace points to the line the Except is on (well the line below that's reporting it).
Code looks a little like this:
try:
...
except Exception as e:
print(f"Error {str(repr(e))}")Is this legacy code written incorrectly? Is there a reason we don't want to stack trace?
Maybe I'm wrong and this is returning the stacktrace but in a file that I'm not looking at, but I wanted to double check because so far Excepts seem to be a hidderance for me when I'm troubleshooting.