I want to generate a one-line string from an Exception
which tells me what happened where (don't need a full backtrace). The following information would be nice:
str(e)
)Currently I do the following:
import os
...
try:
os.nonexisting()
except Exception as e:
t = e.__traceback__
tbf = e.__traceback__.tb_frame
print('%s:%d: %s in %s(): "%s" ' %
os.path.basename(tbf.f_code.co_filename),
t.tb_lineno,
e.__class__.__name__,
tbf.f_code.co_name, e))
which gives me:
foo.py:203: AttributeError in foo(): "'module' object has no attribute 'nonexisting'"
Is there a more elegant way to print out the details given in this example? I'm thinking about s.th. like
print(e.format('%f: %l: %t %F: "%w"'))
I'd like to avoid importing extra modules except there is one exactly for this purpose.
I think traceback.format_exception_only
does exactly what you want.
try:
os.nonexisting()
except Exception as e:
print(traceback.format_exception_only(e.__class__, e))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With