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

John Reid j.reid@mail.cryst.bbk.ac...
Mon Feb 15 09:17:10 CST 2010

Sorry if this appears multiple times but I seem to have had some 
problems posting to the list...

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:

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:

     run program....
     if in ipython:

Thanks for a great python shell!

More information about the IPython-user mailing list