How can I check if code is executed in the IPython notebook?

The following worked for my needs:

get_ipython().__class__.__name__

It returns 'TerminalInteractiveShell' on a terminal IPython, 'ZMQInteractiveShell' on Jupyter (notebook AND qtconsole) and fails (NameError) on a regular Python interpreter. The method get_ipython() seems to be available in the global namespace by default when IPython is started.

Wrapping it in a simple function:

def is_notebook() -> bool:
    try:
        shell = get_ipython().__class__.__name__
        if shell == 'ZMQInteractiveShell':
            return True   # Jupyter notebook or qtconsole
        elif shell == 'TerminalInteractiveShell':
            return False  # Terminal running IPython
        else:
            return False  # Other type (?)
    except NameError:
        return False      # Probably standard Python interpreter

The above was tested with Python 3.5.2, IPython 5.1.0 and Jupyter 4.2.1 on macOS 10.12 and Ubuntu 14.04.4 LTS

EDIT: This still works fine in 2022 on newer Python/IPython/Jupyter/OS versions


To check if you're in a notebook, which can be important e.g. when determining what sort of progressbar to use, this worked for me:

def in_ipynb():
    try:
        cfg = get_ipython().config 
        if cfg['IPKernelApp']['parent_appname'] == 'ipython-notebook':
            return True
        else:
            return False
    except NameError:
        return False