32

I have a traceback object that I want to show in the nice format I get when calling traceback.format_exc().

Is there a builtin function for this? Or a few lines of code?

Martin Thoma
  • 124,992
  • 159
  • 614
  • 958
olamundo
  • 23,991
  • 34
  • 108
  • 149

5 Answers5

36

format_exc() is really just

etype, value, tb = sys.exc_info()
return ''.join(format_exception(etype, value, tb, limit))

So if you have the exception type, value, and traceback ready, it should be easy. If you have just the exception, notice that format_exception() is essentially:

a_list = ['Traceback (most recent call last):\n']
a_list = a_list + format_tb(tb, limit)

where limit defaults to None.

Paul P
  • 3,346
  • 2
  • 12
  • 26
Martin v. Löwis
  • 124,830
  • 17
  • 198
  • 235
  • 5
    I think I'm the only one that doesn't understand this answer... This answer doesn't say where to import `format_tb`, and is using the built in `list` as a variable. And I still don't understand how to print the traceback. – Nic Scozzaro Sep 26 '21 at 07:23
  • @NicScozzaro - I update the answer so that it doesn't use `list`. Also `format_tb()` is part of the [`traceback`](https://docs.python.org/3/library/traceback.html) module. You can simply `from traceback import format_tb` and then use it. – Paul P Jun 13 '22 at 16:30
9

Have you tried traceback.print_tb or traceback.format_tb?

dbr
  • 165,801
  • 69
  • 278
  • 343
Nadia Alramli
  • 111,714
  • 37
  • 173
  • 152
4

traceback docs give few examples and whole set of functions for formatting traceback objects.

SilentGhost
  • 307,395
  • 66
  • 306
  • 293
4

Couldn't find this anywhere, so I'm posting it here for future people and my future self.

try:
  raise Exception('Not an Exception')
except Exception as err:
  msg = "".join(traceback.format_exception(type(err), err, err.__traceback__))
  print(msg)

This takes your exception and provides a string formatted identically to python's default exception printer/print_tb

Jarwain
  • 65
  • 1
  • 4
-1

See also traceback.print_exc()

user2683246
  • 3,399
  • 29
  • 31