Smart help again
wittempj@hotmail.com
martin.witte at gmail.com
Sun Apr 10 15:50:33 EDT 2005
You can create your own Exception class, based on thisrecipe:
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52215, it will
look like
-import sys, traceback
-
-class Error:
- def __init__(self, arg):
- self._arg = arg
- tb = sys.exc_info()[2]
- while 1:
- if not tb.tb_next:
- break
- tb = tb.tb_next
- stack = []
- f = tb.tb_frame
- while f:
- stack.append(f)
- f = f.f_back
- stack.reverse()
- #traceback.print_exc()
- print "Locals by frame, innermost last"
- for frame in stack:
- print
- print "Frame %s in %s at line %s" % \
- (frame.f_code.co_name, frame.f_code.co_filename,
-frame.f_lineno)
- for key, value in frame.f_locals.items():
- print "\t%20s = " % key,
- #We have to be careful not to cause a new error in our
-error
- #printer! Calling str() on an unknown object could
cause -an
- #error we don't want.
- try:
- print value
- except:
- print "<ERROR WHILE PRINTING VALUE>"-
-
- def __repr__(self):
- return repr(self._arg)
-
suppose this class is in a module named test.py, then your code can be
like:
-#!/usr/bin/env python
-import test, sys
-try:
- try:
- class Spam:
- def eggs(self):
- return 1/0
- foo = Spam()
- foo.eggs()
- except:
- raise test.Error('xxx')
-except test.Error, e:
- print >> sys.stderr, e.__class__.__name__, e
The output will be:
-Locals by frame, innermost last
-
-Frame ? in ./test2.py at line 12
- Spam = __main__.Spam
- __builtins__ = <module '__builtin__' (built-in)>
- __file__ = ./test2.py
- sys = <module 'sys' (built-in)>
- test = <module 'test' from
'/home/martin/test.pyc'>
- __name__ = __main__
- foo = <__main__.Spam instance at 0xb7e0720c>
- __doc__ = None
-Frame eggs in ./test2.py at line 8
- self = <__main__.Spam instance at 0xb7e0720c>
-Error 'xxx'
More information about the Python-list
mailing list