How to use Jupyter notebooks in a conda environment?
Asked Answered
M

5

147

Typically one runs jupyter notebook or jupyter-notebook or ipython notebook in a terminal to start a Jupyter notebook webserver locally (and open the URL in the browser). When using conda and conda environments, what is the best way to run a Jupyter notebook which allows to import Python modules installed in the conda environment?

As it seems, this is not quite straight forward and many users have similar troubles.

Most common error message seems to be: after installing a package XYZ in a conda environment my-env one can run import XYZ in a python console started in my-env, but running the same code in the Jupyter notebook will lead to an ImportError.

This question has been asked many times, but there is no good place to answer it, most Q&A's and Github tickets are quite messy so let's start a new Q&A here.

Minerva answered 23/9, 2019 at 19:16 Comment(0)
M
238

Disclaimer: ATM tested only in Ubuntu and Windows (see comments to this answer).


Jupyter runs the user's code in a separate process called kernel. The kernel can be a different Python installation (in a different conda environment or virtualenv or Python 2 instead of Python 3) or even an interpreter for a different language (e.g. Julia or R). Kernels are configured by specifying the interpreter and a name and some other parameters (see Jupyter documentation) and configuration can be stored system-wide, for the active environment (or virtualenv) or per user. If nb_conda_kernels is used, additional to statically configured kernels, a separate kernel for each conda environment with ipykernel installed will be available in Jupyter notebooks.

In short, there are three options how to use a conda environment and Jupyter:

Option 1: Run Jupyter server and kernel inside the conda environment

Do something like:

conda create -n my-conda-env         # creates new virtual env
conda activate my-conda-env          # activate environment in terminal
conda install jupyter                # install jupyter + notebook
jupyter notebook                     # start server + kernel inside my-conda-env

Jupyter will be completely installed in the conda environment. Different versions of Jupyter can be used for different conda environments, but this option might be a bit of overkill. It is enough to include the kernel in the environment, which is the component wrapping Python which runs the code. The rest of Jupyter notebook can be considered as editor or viewer and it is not necessary to install this separately for every environment and include it in every env.yml file. Therefore one of the next two options might be preferable, but this one is the simplest one and definitely fine.

Option 2: Create special kernel for the conda environment

Do something like:

conda create -n my-conda-env                               # creates new virtual env
conda activate my-conda-env                                # activate environment in terminal
conda install ipykernel                                    # install Python kernel in new conda env
ipython kernel install --user --name=my-conda-env-kernel   # configure Jupyter to use Python kernel

Then run jupyter from the system installation or a different conda environment:

conda deactivate          # this step can be omitted by using a different terminal window than before
conda install jupyter     # optional, might be installed already in system e.g. by 'apt install jupyter' on debian-based systems
jupyter notebook          # run jupyter from system

Name of the kernel and the conda environment are independent from each other, but it might make sense to use a similar name.

Only the Python kernel will be run inside the conda environment, Jupyter from system or a different conda environment will be used - it is not installed in the conda environment. By calling ipython kernel install the jupyter is configured to use the conda environment as kernel, see Jupyter documentation and IPython documentation for more information. In most Linux installations this configuration is a *.json file in ~/.local/share/jupyter/kernels/my-conda-env-kernel/kernel.json:

{
 "argv": [
  "/opt/miniconda3/envs/my-conda-env/bin/python",
  "-m",
  "ipykernel_launcher",
  "-f",
  "{connection_file}"
 ],
 "display_name": "my-conda-env-kernel",
 "language": "python"
}

Option 3: Use nb_conda_kernels to use a kernel in the conda environment

When the package nb_conda_kernels is installed, a separate kernel is available automatically for each conda environment containing the conda package ipykernel or a different kernel (R, Julia, ...).

conda activate my-conda-env    # this is the environment for your project and code
conda install ipykernel
conda deactivate

conda activate base            # could be also some other environment
conda install nb_conda_kernels
jupyter notebook

You should be able to choose the Kernel Python [conda env:my-conda-env]. Note that nb_conda_kernels seems to be available only via conda and not via pip or other package managers like apt.

Troubleshooting

Using Linux/Mac the command which on the command line will tell you which jupyter is used, if you are using option 1 (running Jupyter from inside the conda environment), it should be an executable from your conda environment:

$ which jupyter
/opt/miniconda3/envs/my-conda-env/bin/jupyter
$ which jupyter-notebook   # this might be different than 'which jupyter'! (see below)
/opt/miniconda3/envs/my-conda-env/bin/jupyter-notebook

Inside the notebook you should see that Python uses Python paths from the conda environment:

[1] !which python
/opt/miniconda3/envs/my-conda-env/bin/python
[2] import sys; sys.executable
'/opt/miniconda3/envs/my-conda-env/bin/python'
['/home/my_user',
 '/opt/miniconda3/envs/my-conda-env/lib/python37.zip',
 '/opt/miniconda3/envs/my-conda-env/lib/python3.7',
 '/opt/miniconda3/envs/my-conda-env/lib/python3.7/lib-dynload',
 '',
 '/opt/miniconda3/envs/my-conda-env/lib/python3.7/site-packages',
 '/opt/miniconda3/envs/my-conda-env/lib/python3.7/site-packages/IPython/extensions',
 '/home/my_user/.ipython']

Jupyter provides the command jupyter-troubleshoot or in a Jupyter notebook:

!jupyter-troubleshoot

This will print a lot of helpful information about including the outputs mentioned above as well as installed libraries and others. When asking for help regarding Jupyter installations questions, it might be good idea to provide this information in bug reports or questions.

To list all configured Jupyter kernels run:

jupyter kernelspec list

Common errors and traps

Jupyter notebook not installed in conda environment

Note: symptoms are not unique to the issue described here.

Symptoms: ImportError in Jupyter notebooks for modules installed in the conda environment (but not installed system wide), but no error when importing in a Python terminal

Explaination: You tried to run jupyter notebook from inside your conda environment (option 1, see above), there is no configuration for a kernel for this conda environment (this would be option 2) and nb_conda_kernels is not installed (option 3), but jupyter notebook is not (fully) installed in the conda environment, even if which jupyter might make you believe it was.

In GNU/Linux you can type which jupyter to check which executable of Jupyter is run.

This means that system's Jupyter is used, probably because Jupyter is not installed:

(my-conda-env) $ which jupyter-notebook
/usr/bin/jupyter

If the path points to a file in your conda environment, Jupyter is run from inside Jupyter:

(my-conda-env) $ which jupyter-notebook
/opt/miniconda3/envs/my-conda-env/bin/jupyter-notebook

Note that when the conda package ipykernel is installed, an executable jupyter is shipped, but no executable jupyter-notebook. This means that which jupyter will return a path to the conda environment but jupyter notebook will start system's jupyter-nootebook (see also here):

 $ conda create -n my-conda-env
 $ conda activate my-conda-env
 $ conda install ipykernel
 $ which jupyter            # this looks good, but is misleading!
 /opt/miniconda3/envs/my-conda-env/bin/jupyter
 $ which jupyter-notebook   # jupyter simply runs jupyter-notebook from system...
 /usr/bin/jupyter-notebook

This happens because jupyter notebook searches for jupyter-notebook, finds /usr/bin/jupyter-notebook and calls it starting a new Python process. The shebang in /usr/bin/jupyter-notebook is #!/usr/bin/python3 and not a dynamic #!/usr/bin/env python. Therefore Python manages to break out of the conda environment. I guess jupyter could call python /usr/bin/jupyter-notebook instead to overrule the shebang, but mixing system's bin files and the environment's python path can't work well anyway.

Solution: Install jupyter notebook inside the conda environment:

 conda activate my-conda-env
 conda install jupyter
 jupyter notebook

Wrong kernel configuration: Kernel is configured to use system Python

Note: symptoms are not unique to the issue described here.

Symptoms: ImportError in Jupyter notebooks for modules installed in the conda environment (but not installed system wide), but no error when importing in a Python terminal

Explanation: Typically the system provides a kernel called python3 (display name "Python 3") configured to use /usr/bin/python3, see e.g. /usr/share/jupyter/kernels/python3/kernel.json. This is usually overridden by a kernel in the conda environment, which points to the environments python binary /opt/miniconda3/envs/my-conda-env/bin/python. Both are generated by the package ipykernel (see here and here).

A user kernel specification in ~/.local/share/jupyter/kernels/python3/kernel.json might override the system-wide and environment kernel. If the environment kernel is missing or the user kernel points to a python installation outside the environment option 1 (installation of jupyter in the environment) will fail.

For occurrences and discussions of this problem and variants see here, here, here and also here, here and here.

Solution: Use jupyter kernelspec list to list the location active kernel locations.

$ conda activate my-conda-env
$ jupyter kernelspec list
Available kernels:
  python3 /opt/miniconda3/envs/my-conda-env/share/jupyter/kernels/python3

If the kernel in the environment is missing, you can try creating it manually using ipython kernel install --sys-prefix in the activated environment, but it is probably better to check your installation, because conda install ipykernel should have created the environment (maybe try re-crate the environment and re-install all packages?).

If a user kernel specification is blocking the environment kernel specification, you can either remove it or use a relative python path which will use $PATH to figure out which python to use. So something like this, should be totally fine:

$ cat ~/.local/share/jupyter/kernels/python3/kernel.json
{
 "argv": [
  "python",
  "-m",
  "ipykernel_launcher",
  "-f",
  "{connection_file}"
 ],
 "display_name": "Python 3",
 "language": "python"
}

Correct conda environment not activated

Symptoms: ImportError for modules installed in the conda environment (but not installed system wide) in Jupyter notebooks and Python terminals

Explanation: Each terminal has a set of environment variables, which are lost when the terminal is closed. In order to use a conda environment certain environment variables need to be set, which is done by activating it using conda activate my-conda-env. If you attempted to run Jupyter notebook from inside the conda environment (option 1), but did not activate the conda environment before running it, it might run the system's jupyter.

Solution: Activate conda environment before running Jupyter.

 conda activate my-conda-env
 jupyter notebook

Broken kernel configuration

Symptoms: Strange things happening. Maybe similar symptoms as above, e.g. ImportError

Explanation: If you attempted to use option 2, i.e. running Jupyter from system and the Jupyter kernel inside the conda environment by using an explicit configuration for the kernel, but it does not behave as you expect, the configuration might be corrupted in some way.

Solution: Check configuration in ~/.local/share/jupyter/kernels/my-kernel-name/kernel.json and fix mistakes manually or remove the entire directory and re-create it using the command provided above for option 2. If you can't find the kernel configuration there run jupyter kernelspec list.

Python 2 vs 3

Symptoms: ImportError due to wrong Python version of the Jupyter kernel or other problems with Python 2/3

Explanation: The kernel configuration can have all sorts of confusing and misleading effects. For example the default Python 3 kernel configuration will allow me to launch a Jupyter notebook running on Python 2:

conda create -n my-conda-env
conda activate my-conda-env
conda install python=2
conda install jupyter
jupyter notebook

The default Python 3 kernel:

$ cat ~/.local/share/jupyter/kernels/python3/kernel.json
{
 "argv": [
  "python",
  "-m",
  "ipykernel_launcher",
  "-f",
  "{connection_file}"
 ],
 "display_name": "Python 3",
 "language": "python"
}

After creating a new Jupyter Notebook with the Python 3 kernel, Python 2 from the conda environment will be used even if "Python 3" is displayed by Jupyter.

Solution: Don't use Python 2 ;-)

Minerva answered 23/9, 2019 at 19:18 Comment(24)
Option 3 has a mistake: nb_conda only works because it installs nb_conda_kernels as a dependency. nb_conda_kernels is the only requirement for a Jupyter instance in an env to automatically recognize any env with ipykernel installed (see docs). The nb_conda package is for a Jupyter extension that adds a "Conda" tab to Jupyter, providing an Anaconda Navigator-like GUI for managing envs.Pomegranate
@Pomegranate Uh yes! Thanks a lot for pointing that out, I've fixed the mistake.Minerva
The code in Option 1: conda install juypter should be conda install jupyter.Tripletail
@Minerva I am using AWS EMR Jupyter Notebook, I created a new conda env but i am unable to see that in jupyter ui nor in the kernelspec list. can see it from inside the docker container, ` python3 /opt/conda/share/jupyter/kernels/python3 { "argv": [ "/opt/conda/envs/py38/bin/python", "-m", "ipykernel_launcher", "-f", "{connection_file}" ], "display_name": "Python 3", "language": "python" ` , but when I go to the notebook, I see this system python - ` "argv": [ "/opt/conda/bin/python" `Micromillimeter
@learning sorry, I don't get your question, but I guess even your question is related, it's worth opening a new question and not discussing it here in the comments.Minerva
@Minerva I already opened a Q on this sometime back, but haven't got any answers yet. #63230615Micromillimeter
I confirm this is working fine on windows too. You seem to be losing the !pip install xxx commands but its a good trade off.Tunnell
@Tunnell oh that's weird. Which step broke !pip install xxx? That's another Jupyter issue which I haven't been able to track down, didn't know it's related. Sometimes leaving out the exclamation mark seems to help.Minerva
@Minerva not sure exactly at which step it broke. It looks like the pip install installs modules on the same environment the jupyter session has been launched, regardless of the kernel.Tunnell
@Tunnell Which error do you get? Did you install pip in your environment?Minerva
Option 1 works on Manjaro - thanks; nice clean solutionJenna
None of the Options worked the more "convoluted" package rdkit [conda create -c conda-forge -n my-rdkit-env rdkit ], unfortunately. The package is still only available under python console. Still +1 tho.Cracksman
@Cracksman there is a weird behavior in my setup, which I probably should add to the answer above: after creating a new conda env, I have to close the terminal window and then activate it again, otherwise it won't set paths correctly or so. Didn't figure out why yet. But besides this caveat, I was able to create a conda env, install jupyter and rdkit using mamba (it's faster than conda) and then run jupyter and from rdkit import Chem.Minerva
@Minerva For option 2, just to confirm, I should run conda install jupyter inside the system (before I activate any env), right?Tsang
@HolmesQueen Yes, you are right. The code snippets with commands was a bit misleading. Basically for option 2 you need to decide between (a) system insallation, (b) conda base environment and (c) a different conda env. For (a) you install jupyter without conda (e.g. using apt). For (b) you install jupyter before activating the env or by deactivating it or by opening a new terminal. For (c) you install jupyter after activating a new different env. In any case. you'll need to run jupyter notebook in the right environment you picked. I've updated the instructions slightly.Minerva
As a warning - if you are relying on conda to make all environments with ipykernel installed available in Jupyter, the jupyter kernelspec list will be misleading. jupyter kernelspec list is not aware of conda environments and thus may only show the current environment, yet you may see more kernels in Jupyter.Birdwell
Thanks so much for writing this detailed answer. I tried option 1 and 2 and was getting 500 Internal Server error. I found this answer helpful - #36852246Trever
@Minerva What is the practical difference between Option 2 and 3? Because using nb_conda_kernels, we are unable to interrupt cell execution when using a kernel from a different environment. Is the other option better then?Imprisonment
@JoãoBravo well, option 3 is a bit more convenient: there are kernels for all conda environments without having you to worry about it. But option 2 is a good workaround if you are having troubles with option 3, but you will have to add the kernel manually for each conda environment.Minerva
Within my environment, I installed jupyter using conda install -c conda-forge notebook However, when I run (even within the environment) which jupyter-notebook, the result is still .local/bin/jupyter-notebook instead of the miniconda3/envs/env_name/bin/jupyter-notebook. In particular, if I run directly on the terminal miniconda3/envs/env_name/bin/jupyter-notebook everything works fine. Does anyone have a suggestion on how to configure so that this is run automatically when running jupyter notebook inside of my environment?Joo
@IvanBurbano seems as if activating the environment did not work. Checkout conda activate and then check environment variables after that. You should have an evironment variable CONDA_PYTHON_EXE.Minerva
@Minerva thank you very much for your response. I do have an environment variable CONDA_PYTHON_EXE=/home/user_name/miniconda3/bin/python when in my environment. Could there be another reason?Joo
Interesting. So, when I open the terminal it automatically enters a base conda environment. This does not have a jupyter notebook install. When I enter my environment in which I have downloaded the jupyter notebook, it gives the faulty behaviour. But if, before entering this last environment, I first exit the base environment, then everything works as it should. This is a weird behaviour.Joo
@IvanBurbano I think this is a bug I have experienced too. Unfortunately I can't really tell when it occurs nor did I find any open tickets on github. I think comments here are not the best place to discuss this issue, but you can open another question on SO or a ticket on github with all relevant debugging information included.Minerva
R
7

I had a lot of aches with this one, as it's not clearly documented. Many people will recommend installing Jupyter in every conda environment, and as many will tell you to install Jupyter in your (base) conda environment. Unfortunately, both of these recommendations are possible but wrong and will result in strange behaviour, sooner or later. I learned this by trial and error, and I believe now I know how to do it correctly and the recommended way (Nov 2023!). This works on local machines as well as sets you up to have a workflow also suited for remote computing.

These are some gotchas I learned:

  • Conda discourages installing anything in your base env.
  • Conda encourages to create an env for every application; this includes Jupyter
  • Jupyter did show my kernels that I created with ipykernel install …, but I never could make it actually use the correct environment
  • When I finally switched to nb_conda_kernels (solution 3 from lumbric but not in base env!), everything worked automagically! You just have to install nb_conda_kernels in your jupyter environment and ipykernel for any conda environment that you want to use with Jupyter.

Create Jupyter env

please note and check the conda install … command. I added some useful extensions, but you should install what you want. Make sure to be in the right conda path before creating new environments. If you create your new env in a different directory, you might face the issue that your named env will go away.

cd ~/<miniconda>
conda create -n jupyter python=3.11
conda activate jupyter

conda install --channel=conda-forge jupyterlab jupyterlab-favorites jupyterlab-system-monitor nb_conda_kernels

Now you'll have a jupyter env with python 3.11. If you want to launch Jupyter, just open a terminal and type: jupyter lab Jupyter will run as long as this terminal window is open.

Create project env

cd ~/<my_project>
conda create -n my_project python=3.9
conda activate my_project
conda install <…> #(whatever you want to install for your project; use conda first and only if n/a then pip, then brew, then compile)**
# install support for this env kernel in Jupyter:
conda install ipykernel

**Let's put that warning here twice:

  • if you use conda, do not use pip, brew, etc. (that is when possible).
  • first look for conda install --channel=conda-forge mypackage
  • if that's not available try with conda install mypackage
  • if that's not available, you can use pip install mypackage
  • if that's not available, you can resort to brew install or apt-get … etc...
  • if that's not available, you have to compile the lib yourself.

Launching Jupyter:

conda activate jupyter
jupyter lab

Select environment

… now you can select your env kernels in Jupyter. You'll usually find this in the top right area of your notebook. You should see any environment there that has nb_conda_kernels installed, that look something like this:

Python [conda env:my_project]

Ravelment answered 22/11, 2023 at 10:1 Comment(5)
Is there any downside of using the base env? Note that you don't need to install nb_conda_kernels, you need only ipykernel. If you install nb_conda_kernels in in my_project there is no real need for a second conda env because nb_conda_kernels depends on jupyterlab, so in the end you install jupyterlab in both environments.Minerva
yes, there are indeed a couple of issues - a good explanation is here: (https://mcmap.net/q/75540/-what-39-s-the-purpose-of-the-quot-base-quot-for-best-practices-in-anaconda) and the conda documentation also clearly states "You don't want to put programs into your base environment". On the other hand, having Jupyter in its own environment means I have a separate shell window that I can start/stop, Jupyter's own Python version and so on. I believe this is much cleaner than having Jupyter and a lot of dependencies in base, where it might conflict with other envs.Ravelment
and yes, you're right, I just read up that it's sufficient to have ipykernel installed in the envs that should be available as jupyter kernel. Thanks for the info!Ravelment
the official documentation is not very specfic why not to install anything in base and why it is allowed in the first place, but the SO answer has a good point, but in the end it kinda depends ion whether you want to have multiple Jupyter installations on your machine.Minerva
This answer would be improved by following the better practice of specifying all packages in the conda create command, rather than doing a series of conda create-conda activate-conda install. The latter just give users more opportunity to make a mistake and absolutely takes more compute time since the solve has to run multiple times. Even better, adopt the habit of defining environments as YAML files from the start and use conda env create.Pomegranate
S
3

The following command can also be used as a one liner to create your Conda environment running the latest version of Python and the latest version of Jupyter Notebooks,

conda create -n <env-name> python jupyter

If you want to install specific versions of Python or Jupyter, you can do,

conda create -n <env-name> python=<version> jupyter=<version>

For instance,

conda create -n <env-name> python=3.10.4 jupyter=1.0.0

If there are other packages that you want to use in this environment with your notebooks you can do the following,

conda create -n <env-name> python jupyter <another-package> <another-package> ...

For instance,

conda create -n <env-name> python jupyter scikit-learn

Note that similar to before, these commands will install the latest versions of Python and the relevant packages. If you want specific versions, you can use the =<version> syntax.

Also, you can still install any of the packages that you need using either pip install or conda install once the environment has been created.

After you have created your environment (using any of the methods given above), you can simply run the following commands to activate your environment and run Jupyter Notebooks,

conda activate <env-name>
jupyter notebook 
Spanos answered 15/7, 2022 at 14:22 Comment(1)
This is basically option 1 from my answer, but using a shortcut for conda install. Can be done, if you want to enter one command less. I'd discourage from using pip, if packages are available via conda.Minerva
M
0

Following worked for me :

  1. Activate the environment that you want to use : conda activate <env_name>

  2. pip install ipykernel (if you don't already have it)

  3. python -m ipykernel install --user --name=<env_name>

Mordent answered 30/12, 2021 at 8:53 Comment(2)
I just felt the answer was too long, and didn't read till that point .. from my own search I got with those 3 commands which would be helpful for someone looking for a quick answer rather than whole article on it.Mordent
This is a great cliff's notes version of the more widely upvoted answer. One recommendation for improvement: If you are already using conda why not use conda install ipykernel? If you install ipykernel using conda step 3 becomes unnecessary (though you still can do it if you want)Birdwell
B
0

conda activate my-conda-env # this is the environment for your project and code

conda install ipykernel

whereis python # to use your python of current conda environment,the out put is just like below

python: /usr/bin/python /usr/bin/python2.7 /usr/bin/python2.7-config /usr/bin/python3.6 /usr/bin/python3.6m /usr/lib/python2.7 /usr/lib/python3.6 /usr/lib64/python2.7 /usr/lib64/python3.6 /etc/python /usr/include/python2.7 /usr/include/python3.6m /home/scx/.conda/envs/py38/bin/python3.8-config /home/scx/.conda/envs/py38/bin/python /home/scx/.conda/envs/py38/bin/python3.8 /home/anaconda3/bin/python3.7m-config /home/anaconda3/bin/python3.7m /home/anaconda3/bin/python3.7 /home/anaconda3/bin/python3.7-config /home/anaconda3/bin/python /usr/share/man/man1/python.1.gz

[your python environment] -m ipykernel install --name my-conda-env #change [your python environment] to your python envirornment by looking for last output,mine is /home/scx/.conda/envs/py38/bin/python3.8

conda deactivate

conda activate base

jupyter notebook after this, you can select your conda env by click the "New" button.

Brunt answered 2/1, 2024 at 5:41 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.