top of page
Untitled

DATA DOUBLE CONFIRM

Jupyter notebook pointing to wrong virtual environment

I recently cultivated the habit of using virtual environment a.k.a virtualenv (should have done it long time ago for better project management/ best practices). Using virtualenv allows you to avoid installing Python packages globally which could break system tools or other projects. This is especially important when certain projects require certain versions of packages so there will not be conflict if there's a different environment for each project.

After setting up the virtual environment, I want to work using jupyter notebook but ran into error importing a package that I have already installed in the virtualenv (an error message saying no such module shows up). This is because the jupyter notebook is not in that respective virtual environment. I managed to import the library in Python within Anaconda Prompt but not in jupyter notebook so I reckoned that's the issue. I also run help("modules") within jupyter notebook to check if the package is available but it was not listed. Hence this confirmed that the jupyter notebook is pointing to the wrong virtual environment.

To overcome this problem, we have to install the ipykernel within the virtualenv. This is done with the following two lines of code. (And of course, we have to activate the virtualenv first.)

pip install ipykernel

python -m ipykernel install --user --name ENVNAME --display-name "Python (whatever you want to call it)"

PS: On how to set up virtualenv, within Anaconda Prompt, run python -m venv env (or py -m venv env)

References:

https://packaging.python.org/guides/installing-using-pip-and-virtual-environments/

https://stackoverflow.com/questions/37891550/jupyter-notebook-running-kernel-in-different-env

bottom of page