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

StackOverflow

I have some Python code example I"d like to share that should do something different if executed in the terminal Python / IPython or in the IPython notebook.

How can I check from my Python code if it"s running in the IPython notebook?

Answer rating: 85

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_python() seems to be available in the global namespace by default when IPython is started.

Wrapping it in a simple function:

def isnotebook():
    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





Get Solution for free from DataCamp guru