ignoring_gravity
ignoring_gravity

Reputation: 10573

Check if module is installed in Jupyter, rather than in kernel

I have a base conda environment, from which I have run jupyter lab:

(base) $ jupyter lab

Then, from another virtual environment, I have done

(venv) $ pip install ipywidgets
(venv) $ pip install ipykernel
(venv) $ python -m ipykernel install --user --name my-kernel

So, then, in Jupyter Lab (which was started from my base environment), I can open a notebook and select my-kernel as the kernel.

From within such a notebook(which is running my-kernel), how can I detect whether JupyterLab (which was started from my base environment) has ipywidgets installed?

I cannot just do import ipywidgets and see if I get ModuleNotFoundError because that would only detect whether ipywidgets was installed in my-kernel - however, I'm trying to find out if it is installed in my base environment.

Upvotes: 0

Views: 915

Answers (2)

James
James

Reputation: 36756

It partially depends on how you are creating your virtual environments and which OS you are using. I.e. for conda users, this will be different. You can make a subprocess call to pip in the base environment and return a list of installed packages.

import sys
import subprocess
from pathlib import Path

def is_installed_in_base(pkg_name):
    pip = Path(sys.base_prefix).joinpath('bin', 'pip')  # Linux
    # pip = Path(sys.base_prefix).joinpath('Scripts', 'pip.exe')  # Windows
    proc = subprocess.Popen(
        [pip.as_posix(), 'list'], 
        stdout=subprocess.PIPE,
        stderr=subprocess.PIPE
    )
    out, err = proc.communicate()
    packages = out.decode().lower().split('\n')[2:]
    packages = [pkg.split()[0].strip() for pkg in packages if pkg]
    return pkg_name.lower() in packages

is_installed_in_base('ipywidgets')
# returns:
True

Upvotes: 1

Joran Beasley
Joran Beasley

Reputation: 114058

I guess maybe

import ipywidgets
print(ipywidgets.__file__)

Upvotes: 0

Related Questions