MRocklin
MRocklin

Reputation: 57251

Determine if we're in an IPython notebook session

I want my function to do one thing if it's called from the IPython notebook and another thing if its called from a console or library code. In particular I'm making a progress bar with the desired following behavior:

Is there a flag somewhere I can check to determine if the user called my function from a notebook or otherwise?

Upvotes: 1

Views: 708

Answers (1)

minrk
minrk

Reputation: 38588

You can't detect that the frontend is a notebook with perfect precision, because an IPython Kernel can have one or more different Jupyter frontends with different capabilities (terminal console, qtconsole, notebook, etc.). You can, however, identify that it is a Kernel and not plain terminal IPython:

import sys

def is_kernel():
    if 'IPython' not in sys.modules:
        # IPython hasn't been imported, definitely not
        return False
    from IPython import get_ipython
    # check for `kernel` attribute on the IPython instance
    return getattr(get_ipython(), 'kernel', None) is not None

Since the notebook is so much more popular than other frontends, this indicates that the frontend is probably a notebook, but not conclusively. So you want to be sure there's a way out for the more primitive frontends.

Upvotes: 7

Related Questions