Find out if my code runs inside a notebook or jupyter lab?

I found something that works well enough for me:

try:
    from IPython import get_ipython
    ip = get_ipython()
    if ip is None:
            # we have IPython installed but not running from IPython
            return False
        else:
            from IPython.core.interactiveshell import InteractiveShell
            format = InteractiveShell.instance().display_formatter.format
            if len(format(_checkhtml, include="text/html")[0]):
                # TODO: need to check for qtconsole here!
                return True
            else:
                return False
    except:
        # We do not even have IPython installed
        return False

I think this incorrectly returns true if we are running in a qtconsole, but qtconsole can NOT show HTML, so we should check for that separately.
I ignored this for now, cause, how is really using qtconsole? :slight_smile:
Otherwise I think it does what I need.
Feedback welcome!

1 Like