Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I modify a Python traceback object when raising an exception?

I'm working on a Python library used by third-party developers to write extensions for our core application.

I'd like to know if it's possible to modify the traceback when raising exceptions, so the last stack frame is the call to the library function in the developer's code, rather than the line in the library that raised the exception. There are also a few frames at the bottom of the stack containing references to functions used when first loading the code that I'd ideally like to remove too.

Thanks in advance for any advice!

like image 895
James Clarke Avatar asked Oct 21 '09 22:10

James Clarke


People also ask

How do I fix Python traceback error?

If there is no variable defined with that name you will get a NameError exception. To fix the problem, in Python 2, you can use raw_input() . This returns the string entered by the user and does not attempt to evaluate it. Note that if you were using Python 3, input() behaves the same as raw_input() does in Python 2.

How do I log traceback exception in Python?

This is how I do it. try: do_something() except: # How can I log my exception here, complete with its traceback? import traceback traceback. format_exc() # this will print a complete trace to stout.

How do you use TB in Python?

print_tb(tb, limit = None, file = None) : If limit is positive it prints upto limit stack trace entries from traceback object tb. Otherwise, print the last abs(limit) entries. If limit is omitted or None, all entries are printed. If file is omitted or None, the output goes to sys.


1 Answers

You can remove the top of the traceback easily with by raising with the tb_next element of the traceback:

except:     ei = sys.exc_info()     raise ei[0], ei[1], ei[2].tb_next 

tb_next is a read_only attribute, so I don't know of a way to remove stuff from the bottom. You might be able to screw with the properties mechanism to allow access to the property, but I don't know how to do that.

like image 90
user961826 Avatar answered Oct 08 '22 03:10

user961826