How can I run the if run from ipython test in Python?

To make debugging easier with Ipython, I include the following at the beginning of my scripts

from IPython.Debugger import Tracer
debug = Tracer()

However, if I run my script from the command line using

$ python myscript.py

I am getting an error related to Ipython. Is there any way to do the following

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

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

+24
source share
3 answers

This is probably what you are looking for:

def run_from_ipython():
    try:
        __IPYTHON__
        return True
    except NameError:
        return False
+47
source

Python's way is to use exceptions. How:

try:
    from IPython.Debugger import Tracer
    debug = Tracer()
except ImportError:
    pass # or set "debug" to something else or whatever
+11
source

, ( __IPYTHON__) -

def in_ipython():
    return hasattr(globals()["__builtins__"], "__IPYTHON__")

, Tom Dunham:

from timeit import timeit
timeit(in_ipython, number=100000)
> 0.026131024002097547
def toms_in_ipython():
    try:
        return __IPYTHON__
    except NameError:
        return False
timeit(toms_in_ipython, number=100000)
> 0.013109331019222736
0
source

Source: https://habr.com/ru/post/1672170/


All Articles