olamundo
olamundo

Reputation: 24991

How to format traceback objects in Python

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?

Upvotes: 36

Views: 38916

Answers (5)

Martin v. Löwis
Martin v. Löwis

Reputation: 127527

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.


Example:

To further aid in clarifying a (simple) application of format_exc():

import traceback

try:
    # Some code
except Exception:
    print('\nThe following error occurred:\n',
          traceback.format_exc(),
          'Processing aborted.\n',
          sep='\n')
    # sys.exit(1)

Upvotes: 39

user2683246
user2683246

Reputation: 3568

See also traceback.print_exc()

Upvotes: -1

Jarwain
Jarwain

Reputation: 95

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

Upvotes: 7

Nadia Alramli
Nadia Alramli

Reputation: 114981

Have you tried traceback.print_tb or traceback.format_tb?

Upvotes: 9

SilentGhost
SilentGhost

Reputation: 319881

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

Upvotes: 4

Related Questions