views:

816

answers:

3

Catching an exception that would print like this:

Traceback (most recent call last):
  File "c:/tmp.py", line 1, in <module>
    4 / 0
ZeroDivisionError: integer division or modulo by zero

I want to format it into:

ZeroDivisonError, tmp.py, 1
+6  A: 
import sys, os
try:
    raise NotImplementedError("No error")
except Exception, e:
    exc_type, exc_obj, exc_tb = sys.exc_info()
    fname = os.path.split(tb.tb_frame.f_code.co_filename)[1]        
    print(exc_type, fname, tb.tb_lineno)
Ants Aasma
You should be careful about unpacking sys.exc_info() into local variables, since if you get an exception in the except handler, the local vars could get kept in a circular reference and not GC'd. Best practice is to always just use slices off of sys.exc_info() instead. Or use other modules like traceback, as other posters have suggested.
Daniel Pryden
is tb just exc_tb?and os.path.split(blabla)[1] is os.path.basename(balbal)
sunqiang
+2  A: 
try:
    bla
except Exception, e:
    import traceback, os.path
    top = traceback.extract_stack()[-1]
    print ", ".join([type(e).__name__, os.path.basename(top[0]), str(top[1])])
balpha
+1  A: 

Use the built-in traceback module.

Ned Deily