[IPython-user] Test in code at runtime if inside ipython?

John Reid j.reid@mail.cryst.bbk.ac...
Mon Feb 15 07:31:28 CST 2010


I like to log errors in my programs like this:

import logging

def log_exception(exc_type, exc_obj, exc_tb):
     "Log an exception. Used as replacement for sys.excepthook."
     import traceback
     exc_info = traceback.format_exception(exc_type, exc_obj, exc_tb)
     for l in exc_info:
         logging.error(l.strip())

sys.excepthook = log_exception # make sure we log exceptions. This
doesn't work if running under ipython.


Unfortunately it doesn't work under ipython as sys.excepthook is never
reached. Can I insert my log_exception function into the code that is
called by ipython? Or can I test at runtime whether I am inside an
ipython shell so that I could do something like the following:

try:
     run program....
finally:
     if in ipython:
         log_exception(*sys.exc_info())
     raise


Thanks for a great python shell!
John.



More information about the IPython-user mailing list