Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I do an "if run from ipython" test in Python?

Tags:

python

ipython

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.

like image 861
Viktiglemma Avatar asked Mar 21 '11 11:03

Viktiglemma


2 Answers

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

def run_from_ipython():     try:         __IPYTHON__         return True     except NameError:         return False 
like image 151
Tom Dunham Avatar answered Oct 05 '22 07:10

Tom Dunham


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 
like image 27
Jan Hudec Avatar answered Oct 05 '22 09:10

Jan Hudec