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

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?


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


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

You can check whether python is in interactive mode with the following snippet [1]:

def is_interactive():
    import __main__ as main
    return not hasattr(main, '__file__')

I have found this method very useful because I do a lot of prototyping in the notebook. For testing purposes, I use default parameters. Otherwise, I read the parameters from sys.argv.

from sys import argv

if is_interactive():
    params = [<list of default parameters>]
else:
    params = argv[1:]

Following the implementation of autonotebook, you can tell whether you are in a notebook using the following code.

def in_notebook():
    try:
        from IPython import get_ipython
        if 'IPKernelApp' not in get_ipython().config:  # pragma: no cover
            return False
    except ImportError:
        return False
    except AttributeError:
        return False
    return True

Recently I encountered a bug in Jupyter notebook which needs a workaround, and I wanted to do this without loosing functionality in other shells. I realized that keflavich's solution does not work in this case, because get_ipython() is available only directly from the notebook, and not from imported modules. So I found a way to detect from my module whether it is imported and used from a Jupyter notebook or not:

import sys

def in_notebook():
    """
    Returns ``True`` if the module is running in IPython kernel,
    ``False`` if in IPython shell or other Python shell.
    """
    return 'ipykernel' in sys.modules

# later I found out this:

def ipython_info():
    ip = False
    if 'ipykernel' in sys.modules:
        ip = 'notebook'
    elif 'IPython' in sys.modules:
        ip = 'terminal'
    return ip

Comments are appreciated if this is robust enough.

Similar way it is possible to get some info about the client, and IPython version as well:

import sys

if 'ipykernel' in sys.modules:
    ip = sys.modules['ipykernel']
    ip_version = ip.version_info
    ip_client = ip.write_connection_file.__module__.split('.')[0]

# and this might be useful too:

ip_version = IPython.utils.sysinfo.get_sys_info()['ipython_version']

Tested for python 3.7.3

CPython implementations have the name __builtins__ available as part of their globals which btw. can be retrieved by the function globals().
If a script is running in an Ipython environment then __IPYTHON__ should be an attribute of __builtins__.
The code below therefore returns True if run under Ipython or else it gives False

hasattr(__builtins__,'__IPYTHON__')