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

Shead, Timothy tshead at sandia.gov
Wed May 7 23:33:56 EDT 2014


Works like a charm, many thanks!


Timothy M. Shead
Sandia National Laboratories
1461, Scalable Analysis and Visualization

On May 7, 2014, at 5:25 PM, Paul Ivanov <pi at berkeley.edu<mailto:pi at berkeley.edu>> wrote:

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
IPython-dev mailing list
IPython-dev at scipy.org

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/ipython-dev/attachments/20140508/e57f302c/attachment.html>

More information about the IPython-dev mailing list