Jupyter Notebook is a more interactive and easier-to-use version of the Python shell. If we want to install packages from Jupyter Notebook itself, we can put an exclamation point (!) before the pip3/conda install command. This command will then act as if it were executed in the terminal.
When you want to install a package that is not for a particular project, rather a package that will be used across directories, the following steps discuss the correct convention.
Here’s what we usually do:
!pip3 install <package_name>
DON’T DO THIS.
Here is how it should actually be done:
import sys
!{sys.executable} -m pip install <package_name>
Or using conda:
import sys
!conda install --yes --prefix {sys.prefix} <package_name>
Going the longer route rather than plain Python ensures that commands are run in the Python installation matching the currently running notebook. So, pip installs the package in the currently-running Jupyter kernel.
This is done to overcome the disconnectedness between Jupyter kernels and Jupyter’s Shell, i.e., the installer points to a different Python version than the one being used in the notebook.