12

I'm looking for a reliable way to figure out if my module is being loaded/run from within a Jupyter notebook, or more specifically, if ipywidgets is available.

This is not a duplicate of other questions: everything else I've found either has no reliable solution, or (more often) they use the "just try it and fail gently" approach that's common in Python. In my case, I'm trying to write the following logic:

if in_jupyter():
    from tqdm import tqdm_notebook as tqdm
else:
    from tqdm import tqdm

I don't think "try and fail" is an appropriate solution here since I don't want to produce any output yet.

The closest I've found to a solution so far is:

from IPython import get_ipython
get_ipython().config['IPKernelApp']['parent_appname'] == 'ipython-notebook'

but this configuration property is some seemingly empty traitlets.config.loader.LazyConfigValue (.get_value(None) is just an empty string).

scnerd
  • 5,836
  • 2
  • 21
  • 36

3 Answers3

17

You could use the following snippet to figure out if you are in jupyter, ipython or in a terminal:

def type_of_script():
    try:
        ipy_str = str(type(get_ipython()))
        if 'zmqshell' in ipy_str:
            return 'jupyter'
        if 'terminal' in ipy_str:
            return 'ipython'
    except:
        return 'terminal'

You can find more indepth info at How can I check if code is executed in the IPython notebook?

beangoben
  • 186
  • 5
15

If you have tqdm >= 4.27.0, you can import from tqdm.auto to handle this:

from tqdm.auto import tqdm

tqdm can then be used as normal. If you are in a notebook, tqdm will be imported from .notebook.

Antimony
  • 394
  • 4
  • 5
3

You could check whether type(get_ipython()) is from ipykernel, e.g. if

type(get_ipython()).__module__.startswith('ipykernel.')

I'm not sure how stable that is though.

emulbreh
  • 3,421
  • 23
  • 27