32

To ease debugging from Ipython, I include the following in the beginning of my scripts

from IPython.Debugger import Tracer
debug = Tracer()

However, if I launch my script from the command line with

$ python myscript.py

I get an error related to Ipython. Is there a way to do the following

if run_from_ipython():
    from IPython.Debugger import Tracer
    debug = Tracer()

This way I only import the Tracer() function when I need it.

Viktiglemma
  • 912
  • 8
  • 19

2 Answers2

59

This is probably the kind of thing you are looking for:

def run_from_ipython():
    try:
        __IPYTHON__
        return True
    except NameError:
        return False
Tom Dunham
  • 5,779
  • 2
  • 30
  • 27
  • 3
    More detailed IPython configuration detection (whether pylab is loaded and in inline mode) is discussed here: http://stackoverflow.com/questions/15341757/how-to-check-that-pylab-backend-of-matplotlib-runs-inline/17826459#17826459 – 0 _ Jul 24 '13 at 06:14
13

The Python way is to use exceptions. Like:

try:
    from IPython.Debugger import Tracer
    debug = Tracer()
except ImportError:
    pass # or set "debug" to something else or whatever
Jan Hudec
  • 73,652
  • 13
  • 125
  • 172