[IPython-dev] How can tell if code is executing within ipython / ipython notebook?

Paul Ivanov pi at berkeley.edu
Wed May 7 19:25:04 EDT 2014

Shead, Timothy, on 2014-05-07 23:01,  wrote:
> I have some code that I’d like to execute only when run from
> within ipython … is there any way to know?  I’m already
> importing the required ipython modules in a try … catch block,
> so my code handles the case where IPython isn’t installed, but
> that doesn’t address the case where ipython is installed but
> not in use.

When running ipython, we expose the function `get_ipython` to get
a handle on the current IPython instance. So in an interactive
setting, you could just check for that and catch a name error.

More generally, you can do this:

    from IPython import get_ipython

Calling get_ipython() will return None if IPython isn't running,
otherwise it will return an IPython shell object.

                  / \
                A*   \^   -
             ,./   _.`\\ / \
            / ,--.S    \/   \
           /  `"~,_     \    \
     __o           ?
   _ \<,_         /:\
--(_)/-(_)----.../ | \
Paul Ivanov

More information about the IPython-dev mailing list