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).
Note: You can also tell whether a cell is currently executing in a Jupyter notebook by inspecting the small circle in the top-right of the window. The circle will turn grey (“Kernel busy”) when the cell is running, and return to empty (“Kernel idle”) when the process is complete.
To check which version of a given package is installed, use the pip show <your_package> command. For example, to check the version of your NumPy installation or virtual environment, run pip show numpy in your command line or Powershell (Windows), or terminal (macOS and Linux/Ubuntu).
Jupyter doesn't load or doesn't work in the browserTry disabling any browser extensions and/or any Jupyter extensions you have installed. Some internet security software can interfere with Jupyter. If you have security software, try turning it off temporarily, and look in the settings for a more long-term solution.
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?
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
.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With